2022-02-21 14:36:29 -06:00
package coderd
import (
"fmt"
"net/http"
2026-04-16 13:59:09 +02:00
"sort"
"strings"
2022-02-21 14:36:29 -06:00
2026-01-08 15:24:11 +04:00
"github.com/mitchellh/mapstructure"
2026-05-13 12:51:44 +02:00
"cdr.dev/slog/v3"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/awsidentity"
"github.com/coder/coder/v2/coderd/azureidentity"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
2022-02-21 14:36:29 -06:00
)
2022-04-19 08:48:13 -05:00
// Azure supports instance identity verification:
// https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service?tabs=linux#tabgroup_14
2023-01-05 15:27:10 +01:00
//
// @Summary Authenticate agent on Azure instance
// @ID authenticate-agent-on-azure-instance
// @Security CoderSessionToken
2023-01-13 12:27:21 +01:00
// @Accept json
2023-01-05 15:27:10 +01:00
// @Produce json
// @Tags Agents
2026-04-16 13:59:09 +02:00
// @Param request body agentsdk.AzureInstanceIdentityToken true "Instance identity token. The optional agent_name field disambiguates when multiple agents share the same instance ID."
2023-01-29 15:47:24 -06:00
// @Success 200 {object} agentsdk.AuthenticateResponse
2026-05-05 02:54:03 +05:00
// @Router /api/v2/workspaceagents/azure-instance-identity [post]
2022-05-25 22:14:08 -05:00
func ( api * API ) postWorkspaceAuthAzureInstanceIdentity ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2023-01-29 15:47:24 -06:00
var req agentsdk . AzureInstanceIdentityToken
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-04-19 08:48:13 -05:00
return
}
2026-05-13 16:14:07 +02:00
instanceID , err := azureidentity . Validate ( r . Context (), req . Signature , api . AzureCertificates )
2022-04-19 08:48:13 -05:00
if err != nil {
2026-05-13 12:51:44 +02:00
// Log the full error for operators but return only a
// generic message to the caller. Errors from the
// certificate fetch path may contain fragments of
// internal HTTP responses, so exposing them would be
// an information disclosure risk.
api . Logger . Warn ( ctx , "azure identity validation failed" ,
slog . Error ( err ),
)
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusUnauthorized , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Invalid Azure identity." ,
2026-05-13 12:51:44 +02:00
Detail : "Signature verification failed." ,
2022-04-19 08:48:13 -05:00
})
return
}
2026-04-16 13:59:09 +02:00
api . handleAuthInstanceID ( rw , r , instanceID , req . AgentName )
2022-04-19 08:48:13 -05:00
}
2023-01-13 12:27:21 +01:00
// AWS supports instance identity verification:
// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html
// Using this, we can exchange a signed instance payload for an agent token.
//
2023-01-05 15:27:10 +01:00
// @Summary Authenticate agent on AWS instance
// @ID authenticate-agent-on-aws-instance
// @Security CoderSessionToken
2023-01-13 12:27:21 +01:00
// @Accept json
2023-01-05 15:27:10 +01:00
// @Produce json
// @Tags Agents
2026-04-16 13:59:09 +02:00
// @Param request body agentsdk.AWSInstanceIdentityToken true "Instance identity token. The optional agent_name field disambiguates when multiple agents share the same instance ID."
2023-01-29 15:47:24 -06:00
// @Success 200 {object} agentsdk.AuthenticateResponse
2026-05-05 02:54:03 +05:00
// @Router /api/v2/workspaceagents/aws-instance-identity [post]
2022-05-25 22:14:08 -05:00
func ( api * API ) postWorkspaceAuthAWSInstanceIdentity ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2023-01-29 15:47:24 -06:00
var req agentsdk . AWSInstanceIdentityToken
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-03-28 13:31:03 -06:00
return
}
identity , err := awsidentity . Validate ( req . Signature , req . Document , api . AWSCertificates )
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusUnauthorized , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Invalid AWS identity." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-03-28 13:31:03 -06:00
})
return
}
2026-04-16 13:59:09 +02:00
api . handleAuthInstanceID ( rw , r , identity . InstanceID , req . AgentName )
2022-03-28 13:31:03 -06:00
}
2023-01-13 12:27:21 +01:00
// Google Compute Engine supports instance identity verification:
// https://cloud.google.com/compute/docs/instances/verifying-instance-identity
// Using this, we can exchange a signed instance payload for an agent token.
//
2023-01-05 15:27:10 +01:00
// @Summary Authenticate agent on Google Cloud instance
// @ID authenticate-agent-on-google-cloud-instance
// @Security CoderSessionToken
2023-01-13 12:27:21 +01:00
// @Accept json
2023-01-05 15:27:10 +01:00
// @Produce json
// @Tags Agents
2026-04-16 13:59:09 +02:00
// @Param request body agentsdk.GoogleInstanceIdentityToken true "Instance identity token. The optional agent_name field disambiguates when multiple agents share the same instance ID."
2023-01-29 15:47:24 -06:00
// @Success 200 {object} agentsdk.AuthenticateResponse
2026-05-05 02:54:03 +05:00
// @Router /api/v2/workspaceagents/google-instance-identity [post]
2022-05-25 22:14:08 -05:00
func ( api * API ) postWorkspaceAuthGoogleInstanceIdentity ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2023-01-29 15:47:24 -06:00
var req agentsdk . GoogleInstanceIdentityToken
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-02-21 14:36:29 -06:00
return
}
// We leave the audience blank. It's not important we validate who made the token.
2022-09-21 17:07:00 -05:00
payload , err := api . GoogleTokenValidator . Validate ( ctx , req . JSONWebToken , "" )
2022-02-21 14:36:29 -06:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusUnauthorized , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Invalid GCP identity." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-02-21 14:36:29 -06:00
})
return
}
claims := struct {
Google struct {
ComputeEngine struct {
InstanceID string `mapstructure:"instance_id"`
} `mapstructure:"compute_engine"`
} `mapstructure:"google"`
}{}
err = mapstructure . Decode ( payload . Claims , & claims )
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Error decoding JWT claims." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-02-21 14:36:29 -06:00
})
return
}
2026-04-16 13:59:09 +02:00
api . handleAuthInstanceID ( rw , r , claims . Google . ComputeEngine . InstanceID , req . AgentName )
2022-03-28 13:31:03 -06:00
}
2026-04-16 13:59:09 +02:00
func ( api * API ) handleAuthInstanceID ( rw http . ResponseWriter , r * http . Request , instanceID string , agentName string ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2026-04-16 13:59:09 +02:00
// Instance identity auth happens before the agent has a session token, so
// these lookups must use a restricted system context.
//nolint:gocritic // Instance identity auth happens before agent auth.
systemCtx := dbauthz . AsSystemRestricted ( ctx )
agentName = strings . TrimSpace ( agentName )
2026-05-12 14:55:56 +02:00
agents , err := api . Database . GetWorkspaceBuildAgentsByInstanceID ( systemCtx , instanceID )
2022-02-28 12:00:52 -06:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2026-05-12 14:55:56 +02:00
Message : "Internal error fetching workspace agent." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-02-28 12:00:52 -06:00
})
return
}
2026-05-12 14:55:56 +02:00
if len ( agents ) == 0 {
2026-04-16 13:59:09 +02:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : fmt . Sprintf ( "Instance with id %q not found." , instanceID ),
})
return
}
2026-05-12 14:55:56 +02:00
selected := agents [ 0 ]
2026-04-16 13:59:09 +02:00
if agentName != "" {
2026-05-12 14:55:56 +02:00
found := false
for _ , candidate := range agents {
if candidate . WorkspaceAgent . Name == agentName {
2026-05-06 05:15:39 +10:00
selected = candidate
2026-05-12 14:55:56 +02:00
found = true
2026-04-16 13:59:09 +02:00
break
}
}
2026-05-12 14:55:56 +02:00
if ! found {
2026-04-16 13:59:09 +02:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : fmt . Sprintf ( "No agent found with instance ID %q and name %q." , instanceID , agentName ),
})
return
}
2026-05-12 14:55:56 +02:00
} else if len ( agents ) != 1 {
// Include agent names in the error message to help operators
// configure CODER_AGENT_NAME. The caller has already proven
// cloud instance identity, so agent names are not sensitive
// here.
names := make ([] string , len ( agents ))
for i , candidate := range agents {
names [ i ] = candidate . WorkspaceAgent . Name
2026-04-16 13:59:09 +02:00
}
2026-05-12 14:55:56 +02:00
sort . Strings ( names )
httpapi . Write ( ctx , rw , http . StatusConflict , codersdk . Response {
Message : fmt . Sprintf (
"Multiple agents found with instance ID %q. Set CODER_AGENT_NAME to one of: %s" ,
instanceID ,
strings . Join ( names , ", " ),
),
2022-02-21 14:36:29 -06:00
})
return
}
2026-05-12 14:55:56 +02:00
agent := selected . WorkspaceAgent
2022-02-21 14:36:29 -06:00
// This token should only be exchanged if the instance ID is valid
// for the latest history. If an instance ID is recycled by a cloud,
// we'd hate to leak access to a user's workspace.
2026-05-12 14:55:56 +02:00
latestHistory , err := api . Database . GetLatestWorkspaceBuildByWorkspaceID ( systemCtx , selected . WorkspaceTable . ID )
2022-02-21 14:36:29 -06:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching the latest workspace build." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-02-21 14:36:29 -06:00
})
return
}
2026-05-12 14:55:56 +02:00
if latestHistory . ID != selected . WorkspaceBuildID {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : fmt . Sprintf ( "Resource found for id %q, but isn't registered on the latest history." , instanceID ),
2022-02-21 14:36:29 -06:00
})
return
}
2022-04-12 10:17:33 -05:00
2023-01-29 15:47:24 -06:00
httpapi . Write ( ctx , rw , http . StatusOK , agentsdk . AuthenticateResponse {
2022-02-28 12:00:52 -06:00
SessionToken : agent . AuthToken . String (),
2022-02-21 14:36:29 -06:00
})
}