Setting Up Sourcegraph Securely
Supported on Enterprise plans.
This page lists the settings that strengthen the security posture of a Sourcegraph instance and what each one protects against. Work through it when you deploy a new instance, and review it after major changes to authentication, code hosts, or network topology.
Most settings on this page are in the advanced configuration. See how to view and edit the advanced configuration, and the advanced configuration reference for every setting's description and default.
Items tagged Self-hosted apply only to self-hosted instances. On Sourcegraph Cloud, Sourcegraph manages them for you.
Before you expose the instance
- Self-hosted Create the first administrator account before anyone else can reach the instance. Until an account exists, every visitor sees the setup page, and the first account created there becomes a site administrator, whatever the sign-up settings are. Complete the setup page while the instance is reachable only by you.
- Self-hosted Serve Sourcegraph over HTTPS only. Terminate TLS at the reverse proxy in front of Sourcegraph, redirect HTTP to HTTPS, and send an HSTS header. See HTTP and HTTPS configuration.
- Self-hosted Set
externalURLto thehttps://URL of the instance, such ashttps://sourcegraph.example.com. Sourcegraph sets theSecureattribute on its session cookie whenexternalURLuseshttps, so browsers never send the cookie over plain HTTP.
Control who can sign in
- Use your identity provider. Sign-in through SAML, OpenID Connect, or your code host's OAuth applies your organization's MFA and offboarding to Sourcegraph. See choosing an authentication provider.
- Remove the
builtinprovider, or turn off self sign-up. Once SSO works, removebuiltinfromauth.providersso that no local passwords exist. If you keepbuiltin, setallowSignuptofalseon it explicitly, so that administrators create every account. See builtin password authentication. - Turn off account requests if you don't review them. With sign-up off, the sign-in page lets anyone request an account unless
auth.accessRequest.enabledisfalse. See disable account requests. - Secure organization invitations. Any member of an organization can invite other users to it. Invitations can't create accounts: they only add existing users. There is no setting that turns invitations off, so set
organizationInvitations.signingKeyto a random base64-encoded key, such as the output ofopenssl rand -base64 32. Without a key, Sourcegraph signs invitation links with an empty key, which doesn't protect them. - Restrict sign-up through other providers too.
allowSignuponbuiltindoesn't apply to other providers. SetallowSignupon each provider, and limit code host OAuth to your organization, such as withallowOrgsfor GitHub orallowGroupsfor GitLab. With github.com and open sign-up, anyone with a GitHub account can sign in. - Require verified email addresses from OpenID Connect. Sourcegraph links an OpenID Connect identity to the account with the same email address. Set
requireEmailVerifiedtotrueon eachopenidconnectprovider, so that Sourcegraph rejects a sign-in unless the provider returnsemail_verified: true, and no one can claim an email address they don't own. Microsoft Entra ID doesn't send theemail_verifiedclaim by default, so with this setting on, Entra ID users cannot sign in. For Entra ID, leave it off, or use SAML instead. - Deprovision users automatically. SCIM deactivates Sourcegraph users when they are removed in your identity provider. Use a long random value for
scim.authToken, since it grants user management. - Keep
auth.enableUsernameChangesoff when you sync repository permissions or sign in with SSO. A user who renames their account could take a username that maps to another person's permissions. See Authentication and authorization.
Strengthen local passwords
If you keep the builtin provider:
- Require strong passwords. Raise
auth.minPasswordLength, and enableauth.passwordPolicyto require numbers, mixed case, and special characters. - Tune account lockout.
auth.lockoutlocks an account after repeated failed sign-in attempts. To let users unlock their account by email, setauth.unlockAccountLinkSigningKey. See account lockout. - Keep password reset links short-lived with
auth.passwordResetLinkExpiry.
Limit sessions and tokens
-
Shorten sessions.
auth.sessionExpirylimits how long a session lasts, andauth.maxSessionIdleDurationsigns out sessions that make no requests. Both accept Go durations of at least one hour:JSON{ "auth.sessionExpiry": "168h", "auth.maxSessionIdleDuration": "8h" } -
Restrict access tokens. In
auth.accessTokens, setallowtosite-admin-createornoneif regular users don't need tokens. SetallowNoExpirationtofalseexplicitly, so that no one can create a token that never expires, and shortenexpirationOptionDaysanddefaultExpirationDaysto match your policy. See managing access tokens. -
Require OAuth for the src CLI. Set
srcCli.allowAccessTokenAuthtofalseto reject access tokens sent by the src CLI, so that users sign in withsrc logininstead of storing a long-lived token. The src CLI is identified by itsUser-Agent, so treat this as a policy nudge, not a hard boundary. -
Use service accounts for automation. Give CI and integrations a service account with only the roles it needs, instead of a person's token.
-
Review OAuth apps. Remove OAuth apps that are no longer used.
Restrict network access
Allow only known IP addresses
Self-hosted auth.allowedIpAddress rejects every request whose address is not on the allowlist. It runs before authentication, so it also covers the sign-in page and the API.
JSON{ "auth.allowedIpAddress": { "enabled": true, // Addresses that may open connections to Sourcegraph, such as your load balancer. "clientIpAddress": ["10.0.0.0/24"], // Addresses of end users, read from userIpRequestHeaders. "userIpAddress": ["203.0.113.0/24"], "userIpRequestHeaders": ["X-Forwarded-For"], // Internal services that skip the user check, such as the Kubernetes pod range. "trustedClientIpAddress": ["10.8.0.0/14"], "errorMessageTemplate": "Access from {{.UserIP}} is not allowed. Contact your Sourcegraph administrator." } }
Before you enable it:
- Include the addresses of Sourcegraph's own services in
trustedClientIpAddress, such as the pod range on Kubernetes, and the addresses of executors. Otherwise, services cannot reach the frontend. Sourcegraph always allows127.0.0.1. - Only read the user address from a header your proxy controls. Sourcegraph takes the first address in the first
userIpRequestHeadersheader that is present, and a client can send any value in that header. Configure your proxy to replace the header with the client's address, not append to it, and setclientIpAddressto the proxy's addresses so that clients cannot bypass it. - Know how to recover. If you block your own address, edit the advanced configuration without the web UI.
Other network settings
- Keep
corsOriginlimited to the origins of the code host integrations you use. Each origin listed can send cross-origin requests with users' cookies. - Leave
auth.allowEmbeddedAuthoff unless an internal application must embed the sign-in page. It protects the sign-in and sign-up pages from clickjacking. - Self-hosted Filter outbound connections.
EXTERNAL_DENY_LISTandUNTRUSTED_EXTERNAL_ALLOW_LISTlimit which hosts Sourcegraph and user-supplied URLs can reach. See outgoing connection filtering. - Verify TLS to internal services. Add your internal root CA to
tls.external.certificatesinstead of settinginsecureSkipVerify. See trusting TLS certificates using internal PKI.
Protect code and data
- Enforce repository permissions on every code host connection. A new code host connection doesn't enforce repository permissions: every user can see every repository it syncs, including repositories that are private on the code host. Add
authorizationto each connection's configuration (enforcePermissionsfor Azure DevOps) and configure the matching authentication provider. See getting started with repository permissions. - Decide whether administrators bypass permissions. By default, site administrators can see every repository. Set
authz.enforceForSiteAdminstotrueto apply repository permissions to them as well. See administrators and repository permissions. - Grant features by role. Use access control to limit features such as Batch Changes to the users who need them.
- Self-hosted Encrypt secrets at rest.
encryption.keysencrypts code host tokens, user OAuth tokens, webhook secrets, executor secrets, and other sensitive database columns with a key in Cloud KMS, AWS KMS, or a mounted file. See on-disk database encryption. - Keep sensitive code away from agents. Agent context filters hide the repositories and files you list from the Deep Search and Agentic Batch Changes agents, so that they never reach a model provider.
Reduce the attack surface
- Turn off features you don't use, such as
deepSearch.enabled,batchChanges.enabled, andmcp.enabled. Whenmcp.enabledisfalse, the MCP endpoints return 404. - Limit MCP access. Disable individual tools with
mcp.tools.disabled. Once your MCP clients use pre-registered OAuth clients, disable Dynamic Client Registration. - Self-hosted Don't enable HTML injection. The
htmlHeadTop,htmlHeadBottom,htmlBodyTop, andhtmlBodyBottomsettings add raw HTML and scripts to every page, and take effect only when theENABLE_INJECT_HTMLenvironment variable istrue. Leave that variable unset so that the advanced configuration cannot run scripts in users' browsers. - Require proof of code host access for SCIP uploads. With
lsifEnforceAuthset totrue, users without the upload permission must show a code host token with write access to the repository. See indexing a Go repository for the token the upload needs. - Isolate executors. Use a long random
executors.accessToken, run jobs in Firecracker where you can, and store credentials as executor secrets. - Restrict Batch Changes.
batchChanges.containerRegistryAllowlistlimits which registries batch change steps pull images from, andbatchChanges.restrictMergeToAdminslets only site administrators merge changesets. - Set a secret on every incoming webhook, so that Sourcegraph rejects payloads the code host did not sign. See incoming webhooks.
Monitor the instance
- Send audit logs to your SIEM. The audit log records authentication, user management, and configuration changes, and security event logs record security-relevant actions. On Sourcegraph Cloud, see Cloud audit logs.
- Review outbound requests. The outbound request log shows the requests Sourcegraph makes to code hosts and other services.
- Self-hosted Stay up to date. Security fixes ship in regular releases. See updating Sourcegraph.