2022-01-20 07:46:51 -06:00
package httpapi
import (
"bytes"
2022-09-16 14:54:23 -04:00
"context"
2023-04-13 13:06:16 -05:00
"database/sql"
2022-01-20 07:46:51 -06:00
"encoding/json"
"errors"
2023-03-07 15:10:01 -06:00
"flag"
2022-01-20 07:46:51 -06:00
"fmt"
"net/http"
"reflect"
"strings"
2022-09-16 14:54:23 -04:00
"time"
2022-01-20 07:46:51 -06:00
"github.com/go-playground/validator/v10"
2022-11-01 16:57:38 +02:00
"golang.org/x/xerrors"
2022-07-12 19:15:02 -05:00
2026-01-26 12:11:40 +00:00
"cdr.dev/slog/v3"
2023-09-04 19:39:14 +03:00
"github.com/coder/coder/v2/coderd/httpapi/httpapiconstraints"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/tracing"
"github.com/coder/coder/v2/codersdk"
2026-01-08 15:24:11 +04:00
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
2022-01-20 07:46:51 -06:00
)
2023-02-07 01:58:21 +11:00
var Validate * validator . Validate
2022-01-20 07:46:51 -06:00
// This init is used to create a validator and register validation-specific
// functionality for the HTTP API.
//
// A single validator instance is used, because it caches struct parsing.
func init () {
2023-02-07 01:58:21 +11:00
Validate = validator . New ()
Validate . RegisterTagNameFunc ( func ( fld reflect . StructField ) string {
2022-01-20 07:46:51 -06:00
name := strings . SplitN ( fld . Tag . Get ( "json" ), "," , 2 )[ 0 ]
if name == "-" {
return ""
}
return name
})
2022-11-10 21:51:09 +01:00
2022-08-09 14:25:23 +03:00
nameValidator := func ( fl validator . FieldLevel ) bool {
2022-01-20 07:46:51 -06:00
f := fl . Field (). Interface ()
str , ok := f .( string )
if ! ok {
return false
}
2024-09-04 18:17:53 +10:00
valid := codersdk . NameValid ( str )
2022-10-24 19:46:24 -05:00
return valid == nil
2022-08-09 14:25:23 +03:00
}
2024-08-26 19:38:31 +00:00
for _ , tag := range [] string { "username" , "organization_name" , "template_name" , "workspace_name" , "oauth2_app_name" } {
2023-02-07 01:58:21 +11:00
err := Validate . RegisterValidation ( tag , nameValidator )
2022-08-09 14:25:23 +03:00
if err != nil {
panic ( err )
}
2022-01-20 10:00:13 -06:00
}
2022-11-10 21:51:09 +01:00
2024-06-06 10:59:59 -06:00
displayNameValidator := func ( fl validator . FieldLevel ) bool {
2022-11-10 21:51:09 +01:00
f := fl . Field (). Interface ()
str , ok := f .( string )
if ! ok {
return false
}
2024-09-04 18:17:53 +10:00
valid := codersdk . DisplayNameValid ( str )
2022-11-10 21:51:09 +01:00
return valid == nil
}
2024-06-18 15:36:13 -06:00
for _ , displayNameTag := range [] string { "organization_display_name" , "template_display_name" , "group_display_name" } {
2024-06-06 10:59:59 -06:00
err := Validate . RegisterValidation ( displayNameTag , displayNameValidator )
if err != nil {
panic ( err )
}
2022-11-10 21:51:09 +01:00
}
2023-03-30 13:27:58 +02:00
templateVersionNameValidator := func ( fl validator . FieldLevel ) bool {
f := fl . Field (). Interface ()
str , ok := f .( string )
if ! ok {
return false
}
2024-09-04 18:17:53 +10:00
valid := codersdk . TemplateVersionNameValid ( str )
2023-03-30 13:27:58 +02:00
return valid == nil
}
2024-06-06 10:59:59 -06:00
err := Validate . RegisterValidation ( "template_version_name" , templateVersionNameValidator )
2023-03-30 13:27:58 +02:00
if err != nil {
panic ( err )
}
2024-01-17 13:20:45 +01:00
userRealNameValidator := func ( fl validator . FieldLevel ) bool {
f := fl . Field (). Interface ()
str , ok := f .( string )
if ! ok {
return false
}
2024-09-04 18:17:53 +10:00
valid := codersdk . UserRealNameValid ( str )
2024-01-17 13:20:45 +01:00
return valid == nil
}
err = Validate . RegisterValidation ( "user_real_name" , userRealNameValidator )
if err != nil {
panic ( err )
}
2024-08-26 19:38:31 +00:00
groupNameValidator := func ( fl validator . FieldLevel ) bool {
f := fl . Field (). Interface ()
str , ok := f .( string )
if ! ok {
return false
}
2024-09-04 18:17:53 +10:00
valid := codersdk . GroupNameValid ( str )
2024-08-26 19:38:31 +00:00
return valid == nil
}
err = Validate . RegisterValidation ( "group_name" , groupNameValidator )
if err != nil {
panic ( err )
}
2022-01-20 07:46:51 -06:00
}
2023-04-13 13:06:16 -05:00
// Is404Error returns true if the given error should return a 404 status code.
// Both actual 404s and unauthorized errors should return 404s to not leak
// information about the existence of resources.
func Is404Error ( err error ) bool {
if err == nil {
return false
}
2023-09-04 19:39:14 +03:00
2024-08-07 12:37:55 -05:00
// This tests for dbauthz.IsNotAuthorizedError and rbac.IsUnauthorizedError.
if IsUnauthorizedError ( err ) {
return true
}
return xerrors . Is ( err , sql . ErrNoRows )
}
func IsUnauthorizedError ( err error ) bool {
if err == nil {
return false
}
2023-09-04 19:39:14 +03:00
// This tests for dbauthz.IsNotAuthorizedError and rbac.IsUnauthorizedError.
var unauthorized httpapiconstraints . IsUnauthorizedError
if errors . As ( err , & unauthorized ) && unauthorized . IsUnauthorized () {
return true
}
2024-08-07 12:37:55 -05:00
return false
2023-04-13 13:06:16 -05:00
}
2022-09-21 17:07:00 -05:00
// Convenience error functions don't take contexts since their responses are
// static, it doesn't make much sense to trace them.
2023-05-23 12:06:33 +04:00
var ResourceNotFoundResponse = codersdk . Response { Message : "Resource not found or you do not have access to this resource" }
2022-06-14 10:14:05 -05:00
// ResourceNotFound is intentionally vague. All 404 responses should be identical
// to prevent leaking existence of resources.
func ResourceNotFound ( rw http . ResponseWriter ) {
2023-05-23 12:06:33 +04:00
Write ( context . Background (), rw , http . StatusNotFound , ResourceNotFoundResponse )
2022-06-14 10:14:05 -05:00
}
2025-02-27 05:23:18 -06:00
var ResourceForbiddenResponse = codersdk . Response {
Message : "Forbidden." ,
Detail : "You don't have permission to view this content. If you believe this is a mistake, please contact your administrator or try signing in with different credentials." ,
}
2022-05-17 13:43:19 -05:00
func Forbidden ( rw http . ResponseWriter ) {
2025-02-27 05:23:18 -06:00
Write ( context . Background (), rw , http . StatusForbidden , ResourceForbiddenResponse )
2022-05-17 13:43:19 -05:00
}
2022-08-29 17:00:52 -05:00
func InternalServerError ( rw http . ResponseWriter , err error ) {
var details string
if err != nil {
details = err . Error ()
}
2022-09-21 17:07:00 -05:00
Write ( context . Background (), rw , http . StatusInternalServerError , codersdk . Response {
2022-08-29 17:00:52 -05:00
Message : "An internal server error occurred." ,
Detail : details ,
})
}
2022-09-20 15:16:26 -05:00
func RouteNotFound ( rw http . ResponseWriter ) {
2022-09-21 17:07:00 -05:00
Write ( context . Background (), rw , http . StatusNotFound , codersdk . Response {
2022-09-20 15:16:26 -05:00
Message : "Route not found." ,
})
}
2022-09-21 17:07:00 -05:00
// Write outputs a standardized format to an HTTP response body. ctx is used for
// tracing and can be nil for tracing to be disabled. Tracing this function is
// helpful because JSON marshaling can sometimes take a non-insignificant amount
// of time, and could help us catch outliers. Additionally, we can enrich span
// data a bit more since we have access to the actual interface{} we're
// marshaling, such as the number of elements in an array, which could help us
// spot routes that need to be paginated.
func Write ( ctx context . Context , rw http . ResponseWriter , status int , response interface {}) {
2023-05-30 16:59:39 -05:00
// Pretty up JSON when testing.
if flag . Lookup ( "test.v" ) != nil {
WriteIndent ( ctx , rw , status , response )
return
}
2022-09-21 17:07:00 -05:00
_ , span := tracing . StartSpan ( ctx )
defer span . End ()
2025-05-22 19:48:23 +10:00
SetAuthzCheckRecorderHeader ( ctx , rw )
2025-04-10 10:36:27 -07:00
2023-05-30 16:59:39 -05:00
rw . Header (). Set ( "Content-Type" , "application/json; charset=utf-8" )
rw . WriteHeader ( status )
enc := json . NewEncoder ( rw )
2022-01-20 07:46:51 -06:00
enc . SetEscapeHTML ( true )
2023-05-30 16:59:39 -05:00
2023-07-26 09:21:04 -07:00
// We can't really do much about these errors, it's probably due to a
// dropped connection.
_ = enc . Encode ( response )
2023-05-30 16:59:39 -05:00
}
func WriteIndent ( ctx context . Context , rw http . ResponseWriter , status int , response interface {}) {
_ , span := tracing . StartSpan ( ctx )
defer span . End ()
2025-05-22 19:48:23 +10:00
SetAuthzCheckRecorderHeader ( ctx , rw )
2025-04-10 10:36:27 -07:00
2022-01-20 10:00:13 -06:00
rw . Header (). Set ( "Content-Type" , "application/json; charset=utf-8" )
rw . WriteHeader ( status )
2023-05-30 16:59:39 -05:00
enc := json . NewEncoder ( rw )
enc . SetEscapeHTML ( true )
enc . SetIndent ( "" , "\t" )
2023-07-26 09:21:04 -07:00
// We can't really do much about these errors, it's probably due to a
// dropped connection.
_ = enc . Encode ( response )
2022-01-20 07:46:51 -06:00
}
2022-09-21 17:07:00 -05:00
// Read decodes JSON from the HTTP request into the value provided. It uses
// go-validator to validate the incoming request body. ctx is used for tracing
// and can be nil. Although tracing this function isn't likely too helpful, it
// was done to be consistent with Write.
func Read ( ctx context . Context , rw http . ResponseWriter , r * http . Request , value interface {}) bool {
ctx , span := tracing . StartSpan ( ctx )
defer span . End ()
2022-01-20 07:46:51 -06:00
err := json . NewDecoder ( r . Body ). Decode ( value )
if err != nil {
2022-09-21 17:07:00 -05:00
Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Request body must be valid JSON." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-01-20 07:46:51 -06:00
})
return false
}
2023-02-07 01:58:21 +11:00
err = Validate . Struct ( value )
2022-01-20 07:46:51 -06:00
var validationErrors validator . ValidationErrors
if errors . As ( err , & validationErrors ) {
2022-07-12 19:15:02 -05:00
apiErrors := make ([] codersdk . ValidationError , 0 , len ( validationErrors ))
2022-01-20 07:46:51 -06:00
for _ , validationError := range validationErrors {
2022-07-12 19:15:02 -05:00
apiErrors = append ( apiErrors , codersdk . ValidationError {
2022-04-18 11:02:54 -05:00
Field : validationError . Field (),
2022-05-27 10:13:13 -04:00
Detail : fmt . Sprintf ( "Validation failed for tag %q with value: \"%v\"" , validationError . Tag (), validationError . Value ()),
2022-01-20 07:46:51 -06:00
})
}
2022-09-21 17:07:00 -05:00
Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Validation failed." ,
2022-06-03 16:48:09 -05:00
Validations : apiErrors ,
2022-01-20 07:46:51 -06:00
})
return false
}
if err != nil {
2022-09-21 17:07:00 -05:00
Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error validating request body payload." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-01-20 07:46:51 -06:00
})
return false
}
return true
}
2022-04-01 13:17:45 -05:00
const websocketCloseMaxLen = 123
// WebsocketCloseSprintf formats a websocket close message and ensures it is
// truncated to the maximum allowed length.
func WebsocketCloseSprintf ( format string , vars ... any ) string {
msg := fmt . Sprintf ( format , vars ... )
2024-12-19 00:51:30 +04:00
// Cap msg length at 123 bytes. coder/websocket only allows close messages
2022-04-01 13:17:45 -05:00
// of this length.
if len ( msg ) > websocketCloseMaxLen {
// Trim the string to 123 bytes. If we accidentally cut in the middle of
// a UTF-8 character, remove it from the string.
2023-02-17 11:50:21 -06:00
return strings . ToValidUTF8 ( msg [: websocketCloseMaxLen ], "" )
2022-04-01 13:17:45 -05:00
}
return msg
}
2022-09-16 14:54:23 -04:00
2025-03-28 17:13:20 -04:00
type EventSender func ( rw http . ResponseWriter , r * http . Request ) (
sendEvent func ( sse codersdk . ServerSentEvent ) error ,
done <- chan struct {},
err error ,
)
// ServerSentEventSender establishes a Server-Sent Event connection and allows
// the consumer to send messages to the client.
//
// The function returned allows you to send a single message to the client,
// while the channel lets you listen for when the connection closes.
//
// As much as possible, this function should be avoided in favor of using the
// OneWayWebSocket function. See OneWayWebSocket for more context.
func ServerSentEventSender ( rw http . ResponseWriter , r * http . Request ) (
func ( sse codersdk . ServerSentEvent ) error ,
<- chan struct {},
error ,
) {
2022-09-16 14:54:23 -04:00
h := rw . Header ()
h . Set ( "Content-Type" , "text/event-stream" )
h . Set ( "Cache-Control" , "no-cache" )
h . Set ( "Connection" , "keep-alive" )
h . Set ( "X-Accel-Buffering" , "no" )
f , ok := rw .( http . Flusher )
if ! ok {
panic ( "http.ResponseWriter is not http.Flusher" )
}
2025-03-28 17:13:20 -04:00
ctx := r . Context ()
closed := make ( chan struct {})
2022-11-01 16:57:38 +02:00
type sseEvent struct {
payload [] byte
errC chan error
}
eventC := make ( chan sseEvent )
// Synchronized handling of events (no guarantee of order).
2022-09-16 14:54:23 -04:00
go func () {
2022-11-01 16:57:38 +02:00
defer close ( closed )
2025-03-28 17:13:20 -04:00
ticker := time . NewTicker ( HeartbeatInterval )
2022-09-16 14:54:23 -04:00
defer ticker . Stop ()
for {
2022-11-01 16:57:38 +02:00
var event sseEvent
2022-09-16 14:54:23 -04:00
select {
2025-03-28 17:13:20 -04:00
case <- ctx . Done ():
2022-09-16 14:54:23 -04:00
return
2022-11-01 16:57:38 +02:00
case event = <- eventC :
2022-09-16 14:54:23 -04:00
case <- ticker . C :
2022-11-01 16:57:38 +02:00
event = sseEvent {
payload : [] byte ( fmt . Sprintf ( "event: %s\n\n" , codersdk . ServerSentEventTypePing )),
2022-09-16 14:54:23 -04:00
}
}
2022-11-01 16:57:38 +02:00
_ , err := rw . Write ( event . payload )
if event . errC != nil {
event . errC <- err
}
if err != nil {
return
}
f . Flush ()
2022-09-16 14:54:23 -04:00
}
}()
2025-03-28 17:13:20 -04:00
sendEvent := func ( newEvent codersdk . ServerSentEvent ) error {
2022-09-16 14:54:23 -04:00
buf := & bytes . Buffer {}
2025-03-28 17:13:20 -04:00
_ , err := buf . WriteString ( fmt . Sprintf ( "event: %s\n" , newEvent . Type ))
2022-09-16 14:54:23 -04:00
if err != nil {
return err
}
2025-03-28 17:13:20 -04:00
if newEvent . Data != nil {
2022-11-07 07:25:18 -08:00
_ , err = buf . WriteString ( "data: " )
if err != nil {
return err
}
2025-03-28 17:13:20 -04:00
enc := json . NewEncoder ( buf )
err = enc . Encode ( newEvent . Data )
2022-11-07 07:25:18 -08:00
if err != nil {
return err
}
2022-09-16 14:54:23 -04:00
}
err = buf . WriteByte ( '\n' )
if err != nil {
return err
}
2022-11-01 16:57:38 +02:00
event := sseEvent {
payload : buf . Bytes (),
errC : make ( chan error , 1 ), // Buffered to prevent deadlock.
2022-09-16 14:54:23 -04:00
}
2022-11-01 16:57:38 +02:00
select {
case <- ctx . Done ():
return ctx . Err ()
case <- closed :
return xerrors . New ( "server sent event sender closed" )
case eventC <- event :
// Re-check closure signals after sending the event to allow
// for early exit. We don't check closed here because it
// can't happen while processing the event.
select {
case <- ctx . Done ():
return ctx . Err ()
case err := <- event . errC :
return err
}
}
2022-09-16 14:54:23 -04:00
}
2022-11-01 16:57:38 +02:00
return sendEvent , closed , nil
2022-09-16 14:54:23 -04:00
}
2025-03-28 17:13:20 -04:00
// OneWayWebSocketEventSender establishes a new WebSocket connection that
// enforces one-way communication from the server to the client.
//
// The function returned allows you to send a single message to the client,
// while the channel lets you listen for when the connection closes.
//
// We must use an approach like this instead of Server-Sent Events for the
// browser, because on HTTP/1.1 connections, browsers are locked to no more than
// six HTTP connections for a domain total, across all tabs. If a user were to
// open a workspace in multiple tabs, the entire UI can start to lock up.
// WebSockets have no such limitation, no matter what HTTP protocol was used to
// establish the connection.
2026-01-26 12:11:40 +00:00
func OneWayWebSocketEventSender ( log slog . Logger ) func ( rw http . ResponseWriter , r * http . Request ) (
2025-03-28 17:13:20 -04:00
func ( event codersdk . ServerSentEvent ) error ,
<- chan struct {},
error ,
) {
2026-01-26 12:11:40 +00:00
return func ( rw http . ResponseWriter , r * http . Request ) (
func ( event codersdk . ServerSentEvent ) error ,
<- chan struct {},
error ,
) {
ctx , cancel := context . WithCancel ( r . Context ())
r = r . WithContext ( ctx )
socket , err := websocket . Accept ( rw , r , nil )
2025-03-28 17:13:20 -04:00
if err != nil {
2026-01-26 12:11:40 +00:00
cancel ()
return nil , nil , xerrors . Errorf ( "cannot establish connection: %w" , err )
}
go HeartbeatClose ( ctx , log , cancel , socket )
eventC := make ( chan codersdk . ServerSentEvent )
socketErrC := make ( chan websocket . CloseError , 1 )
closed := make ( chan struct {})
go func () {
defer cancel ()
defer close ( closed )
for {
select {
case event := <- eventC :
writeCtx , cancel := context . WithTimeout ( ctx , 10 * time . Second )
err := wsjson . Write ( writeCtx , socket , event )
cancel ()
if err == nil {
continue
}
_ = socket . Close ( websocket . StatusInternalError , "Unable to send newest message" )
case err := <- socketErrC :
_ = socket . Close ( err . Code , err . Reason )
case <- ctx . Done ():
_ = socket . Close ( websocket . StatusNormalClosure , "Connection closed" )
}
return
2025-03-28 17:13:20 -04:00
}
2026-01-26 12:11:40 +00:00
}()
2025-03-28 17:13:20 -04:00
2026-01-26 12:11:40 +00:00
// We have some tools in the UI code to help enforce one-way WebSocket
// connections, but there's still the possibility that the client could send
// a message when it's not supposed to. If that happens, the client likely
// forgot to use those tools, and communication probably can't be trusted.
// Better to just close the socket and force the UI to fix its mess
go func () {
_ , _ , err := socket . Read ( ctx )
if errors . Is ( err , context . Canceled ) {
return
}
if err != nil {
socketErrC <- websocket . CloseError {
Code : websocket . StatusInternalError ,
Reason : "Unable to process invalid message from client" ,
}
return
}
socketErrC <- websocket . CloseError {
Code : websocket . StatusProtocolError ,
Reason : "Clients cannot send messages for one-way WebSockets" ,
}
}()
sendEvent := func ( event codersdk . ServerSentEvent ) error {
select {
case eventC <- event :
case <- ctx . Done ():
return ctx . Err ()
}
return nil
2025-03-28 17:13:20 -04:00
}
2026-01-26 12:11:40 +00:00
return sendEvent , closed , nil
2025-03-28 17:13:20 -04:00
}
}
2025-07-01 15:39:29 +02:00
// WriteOAuth2Error writes an OAuth2-compliant error response per RFC 6749.
// This should be used for all OAuth2 endpoints (/oauth2/*) to ensure compliance.
2026-01-15 12:41:28 +03:00
func WriteOAuth2Error ( ctx context . Context , rw http . ResponseWriter , status int , errorCode codersdk . OAuth2ErrorCode , description string ) {
2026-02-02 16:01:33 +01:00
// RFC 6749 §5.2: invalid_client SHOULD use 401 and MUST include a
// WWW-Authenticate response header.
if status == http . StatusUnauthorized && errorCode == codersdk . OAuth2ErrorCodeInvalidClient {
rw . Header (). Set ( "WWW-Authenticate" , `Basic realm="coder"` )
}
2026-01-15 12:41:28 +03:00
Write ( ctx , rw , status , codersdk . OAuth2Error {
2025-07-01 15:39:29 +02:00
Error : errorCode ,
ErrorDescription : description ,
})
}