2022-02-21 14:36:29 -06:00
package coderd
import (
2022-02-28 12:00:52 -06:00
"encoding/json"
2022-02-21 14:36:29 -06:00
"fmt"
"net/http"
2026-04-16 13:59:09 +02:00
"sort"
"strings"
2022-02-21 14:36:29 -06:00
2026-04-16 13:59:09 +02:00
"github.com/google/uuid"
2026-01-08 15:24:11 +04:00
"github.com/mitchellh/mapstructure"
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"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/provisionerdserver"
"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
2023-01-05 15:27:10 +01:00
// @Router /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
}
2023-03-08 19:32:10 -06:00
instanceID , err := azureidentity . Validate ( r . Context (), req . Signature , azureidentity . Options {
VerifyOptions : api . AzureCertificates ,
})
2022-04-19 08:48:13 -05: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 Azure identity." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
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
2023-01-05 15:27:10 +01:00
// @Router /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
2023-01-05 15:27:10 +01:00
// @Router /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 )
agents , err := api . Database . GetWorkspaceAgentsByInstanceID ( 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 {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job agent." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-02-28 12:00:52 -06:00
})
return
}
2026-04-16 13:59:09 +02:00
// Template version agents can share an instance ID with workspace build
// agents. Keep only workspace build agents before resolving ambiguity so
// template version agents do not force CODER_AGENT_NAME.
buildAgents := agents [: 0 ]
for _ , candidate := range agents {
resource , err := api . Database . GetWorkspaceResourceByID ( systemCtx , candidate . ResourceID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching provisioner job resource." ,
Detail : err . Error (),
})
return
}
job , err := api . Database . GetProvisionerJobByID ( systemCtx , resource . JobID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching provisioner job." ,
Detail : err . Error (),
})
return
}
if job . Type == database . ProvisionerJobTypeWorkspaceBuild {
buildAgents = append ( buildAgents , candidate )
}
}
agents = buildAgents
if len ( agents ) == 0 {
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : fmt . Sprintf ( "Instance with id %q not found." , instanceID ),
})
return
}
var agent database . WorkspaceAgent
if agentName != "" {
for _ , candidate := range agents {
if candidate . Name == agentName {
agent = candidate
break
}
}
if agent . ID == uuid . Nil {
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : fmt . Sprintf ( "No agent found with instance ID %q and name %q." , instanceID , agentName ),
})
return
}
} 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 . Name
}
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 , ", " ),
),
})
return
}
agent = agents [ 0 ]
}
resource , err := api . Database . GetWorkspaceResourceByID ( systemCtx , agent . ResourceID )
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 {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job resource." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-02-28 12:00:52 -06:00
})
return
}
2026-04-16 13:59:09 +02:00
job , err := api . Database . GetProvisionerJobByID ( systemCtx , resource . JobID )
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 {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-02-28 12:00:52 -06:00
})
return
}
2022-03-07 11:40:54 -06:00
if job . Type != database . ProvisionerJobTypeWorkspaceBuild {
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 ( "%q jobs cannot be authenticated." , job . Type ),
2022-02-28 12:00:52 -06:00
})
return
}
2022-11-07 19:10:49 -06:00
var jobData provisionerdserver . WorkspaceProvisionJob
2022-02-28 12:00:52 -06:00
err = json . Unmarshal ( job . Input , & jobData )
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 extracting job data." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-02-28 12:00:52 -06:00
})
return
}
2026-04-16 13:59:09 +02:00
resourceHistory , err := api . Database . GetWorkspaceBuildByID ( systemCtx , jobData . WorkspaceBuildID )
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 workspace build." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-02-21 14:36:29 -06:00
})
return
}
// 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-04-16 13:59:09 +02:00
latestHistory , err := api . Database . GetLatestWorkspaceBuildByWorkspaceID ( systemCtx , resourceHistory . WorkspaceID )
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
}
2022-05-17 15:00:48 -05:00
if latestHistory . ID != resourceHistory . ID {
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
})
}