Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
.postman/
postman/
.env
.env.*
.DS_Store
.worktrees/
docs/superpowers/
Expand Down
20 changes: 15 additions & 5 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -271,15 +271,25 @@ components:
items:
$ref: "#/components/schemas/SourceReport"
entrance:
$ref: "#/components/schemas/EntranceProps"
nullable: true
allOf:
- $ref: "#/components/schemas/EntranceProps"
pathways:
$ref: "#/components/schemas/PathwayProps"
nullable: true
allOf:
- $ref: "#/components/schemas/PathwayProps"
restroom:
$ref: "#/components/schemas/RestroomProps"
nullable: true
allOf:
- $ref: "#/components/schemas/RestroomProps"
parking:
$ref: "#/components/schemas/ParkingProps"
nullable: true
allOf:
- $ref: "#/components/schemas/ParkingProps"
elevator:
$ref: "#/components/schemas/ElevatorProps"
nullable: true
allOf:
- $ref: "#/components/schemas/ElevatorProps"
updated_at:
type: string
format: date-time
Expand Down
125 changes: 125 additions & 0 deletions cmd/api/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ import (
"time"

"github.com/InWheelOrg/inwheel-api/internal/a11y"
apiv1 "github.com/InWheelOrg/inwheel-api/internal/api/v1"
"github.com/InWheelOrg/inwheel-api/internal/middleware"
"github.com/InWheelOrg/inwheel-api/internal/place"
"github.com/InWheelOrg/inwheel-api/internal/testhelpers"
"github.com/InWheelOrg/inwheel-api/pkg/models"
"github.com/google/uuid"
"golang.org/x/time/rate"
"gopkg.in/yaml.v3"
"gorm.io/gorm"
Expand Down Expand Up @@ -188,6 +190,43 @@ func TestHandlePatchAccessibility_PlaceNotFound(t *testing.T) {
}
}

func TestHandlePatchAccessibility_InvalidPatchReturnsPopulatedFields(t *testing.T) {
t.Cleanup(func() { truncate(t) })

place := models.Place{Name: "Test Place", Lat: 52.5, Lng: 13.4, Category: models.CategoryCafe, Rank: models.RankEstablishment, Source: "test"}
testDB.Create(&place)

srv := newTestServer(t)
id, err := uuid.Parse(place.ID)
if err != nil {
t.Fatalf("parse place id: %v", err)
}

r := httptest.NewRequest(http.MethodPatch, "/v1/places/"+place.ID+"/accessibility", strings.NewReader(`not json`))
ctx := context.WithValue(r.Context(), ctxKeyRawBody{}, []byte(`not json`))
r = r.WithContext(ctx)
ctx = context.WithValue(r.Context(), ctxKeyRequest{}, r)

resp, err := srv.PatchPlaceAccessibility(ctx, apiv1.PatchPlaceAccessibilityRequestObject{
Id: id,
Body: &models.AccessibilityProfile{},
})
if err != nil {
t.Fatalf("PatchPlaceAccessibility: %v", err)
}

got, ok := resp.(apiv1.PatchPlaceAccessibility400JSONResponse)
if !ok {
t.Fatalf("response = %T, want PatchPlaceAccessibility400JSONResponse", resp)
}
if got.Fields == nil {
t.Error("Fields is nil, want a populated (non-null) slice per the ValidationError schema")
}
if len(got.Fields) == 0 {
t.Error("Fields is empty, want at least one entry describing the invalid patch")
}
}

func TestHandlePatchAccessibility_CreatePath(t *testing.T) {
t.Cleanup(func() { truncate(t) })

Expand Down Expand Up @@ -257,6 +296,92 @@ func TestHandlePatchAccessibility_UpdatesExistingProfile(t *testing.T) {
}
}

func TestHandlePatchAccessibility_PartialSubmissionPreservesOtherComponents(t *testing.T) {
t.Cleanup(func() { truncate(t) })

place := models.Place{
Name: "Test Place",
Lat: 52.5,
Lng: 13.4,
Category: models.CategoryCafe,
Rank: models.RankEstablishment,
Source: "test",
Accessibility: &models.AccessibilityProfile{
Entrance: &models.EntranceProps{IsLevel: boolPtr(true)},
Restroom: &models.RestroomProps{IsAccessible: boolPtr(true)},
Parking: &models.ParkingProps{HasDisabledSpaces: boolPtr(true)},
},
}
testDB.Create(&place)

body, _ := json.Marshal(models.AccessibilityProfile{
Entrance: &models.EntranceProps{IsLevel: boolPtr(false)},
})

r := httptest.NewRequest(http.MethodPatch, "/v1/places/"+place.ID+"/accessibility", bytes.NewReader(body))
r.Header.Set("Content-Type", "application/json")
r.SetPathValue("id", place.ID)
w := httptest.NewRecorder()
handlerNoAuth(t, newTestServer(t)).ServeHTTP(w, r)

if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", w.Code, w.Body.String())
}

var profile models.AccessibilityProfile
testDB.Where("place_id = ?", place.ID).First(&profile)

if profile.Entrance == nil || profile.Entrance.IsLevel == nil || *profile.Entrance.IsLevel {
t.Errorf("Entrance.IsLevel = %v, want false (updated)", profile.Entrance)
}
if profile.Restroom == nil || profile.Restroom.IsAccessible == nil || !*profile.Restroom.IsAccessible {
t.Errorf("Restroom = %v, want preserved (IsAccessible=true)", profile.Restroom)
}
if profile.Parking == nil || profile.Parking.HasDisabledSpaces == nil || !*profile.Parking.HasDisabledSpaces {
t.Errorf("Parking = %v, want preserved (HasDisabledSpaces=true)", profile.Parking)
}
}

func TestHandlePatchAccessibility_ExplicitNullClearsComponent(t *testing.T) {
t.Cleanup(func() { truncate(t) })

place := models.Place{
Name: "Test Place",
Lat: 52.5,
Lng: 13.4,
Category: models.CategoryCafe,
Rank: models.RankEstablishment,
Source: "test",
Accessibility: &models.AccessibilityProfile{
Entrance: &models.EntranceProps{IsLevel: boolPtr(true)},
Restroom: &models.RestroomProps{IsAccessible: boolPtr(true)},
},
}
testDB.Create(&place)

body := []byte(`{"restroom":null}`)

r := httptest.NewRequest(http.MethodPatch, "/v1/places/"+place.ID+"/accessibility", bytes.NewReader(body))
r.Header.Set("Content-Type", "application/json")
r.SetPathValue("id", place.ID)
w := httptest.NewRecorder()
handlerNoAuth(t, newTestServer(t)).ServeHTTP(w, r)

if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", w.Code, w.Body.String())
}

var profile models.AccessibilityProfile
testDB.Where("place_id = ?", place.ID).First(&profile)

if profile.Entrance == nil || profile.Entrance.IsLevel == nil || !*profile.Entrance.IsLevel {
t.Errorf("Entrance = %v, want preserved (IsLevel=true)", profile.Entrance)
}
if profile.Restroom != nil {
t.Errorf("Restroom = %v, want nil (explicitly cleared)", profile.Restroom)
}
}

func TestHandleGetPlace_ReturnsPlaceWithAccessibility(t *testing.T) {
t.Cleanup(func() { truncate(t) })

Expand Down
50 changes: 39 additions & 11 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
package main

import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"os"
Expand Down Expand Up @@ -36,12 +38,31 @@ import (
)

type ctxKeyRequest struct{}
type ctxKeyRawBody struct{}

func requestFromCtx(ctx context.Context) *http.Request {
r, _ := ctx.Value(ctxKeyRequest{}).(*http.Request)
return r
}

func rawBodyFromCtx(ctx context.Context) []byte {
b, _ := ctx.Value(ctxKeyRawBody{}).([]byte)
return b
}

func captureRawBody(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "failed to read request body", http.StatusBadRequest)
return
}
_ = r.Body.Close()
r.Body = io.NopCloser(bytes.NewReader(body))
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKeyRawBody{}, body)))
})
}

func injectRequest() apiv1.StrictMiddlewareFunc {
return func(f apiv1.StrictHandlerFunc, operationID string) apiv1.StrictHandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request, req interface{}) (interface{}, error) {
Expand Down Expand Up @@ -169,6 +190,7 @@ func buildV1Handler(srv *Server, corsOrigin string) (http.Handler, error) {
BaseRouter: v1Mux,
ErrorHandlerFunc: srv.validationErrorHandler,
Middlewares: []apiv1.MiddlewareFunc{
captureRawBody,
bodySizeLimiter(1 << 20),
},
})
Expand Down Expand Up @@ -323,33 +345,39 @@ func (s *Server) GetPlace(ctx context.Context, request apiv1.GetPlaceRequestObje

func (s *Server) PatchPlaceAccessibility(ctx context.Context, request apiv1.PatchPlaceAccessibilityRequestObject) (apiv1.PatchPlaceAccessibilityResponseObject, error) {
id := request.Id.String()
input := *request.Body
keyID := middleware.APIKeyIDFromCtx(ctx)

s.engine.WithAuditFlags(&input)

now := time.Now()
if keyID != "" {
input.SubmittedBy = &keyID
input.UserVerified = true
if errs := validation.AccessibilityProfile(request.Body); len(errs) > 0 {
return apiv1.PatchPlaceAccessibility400JSONResponse(validationError(errs)), nil
}
input.SubmittedAt = &now

created, err := s.places.UpsertProfile(ctx, id, &input)
rawPatch := rawBodyFromCtx(requestFromCtx(ctx).Context())
now := time.Now()
profile, created, err := s.places.UpsertProfile(ctx, id, rawPatch, func(p *models.AccessibilityProfile) {
s.engine.WithAuditFlags(p)
if keyID != "" {
p.SubmittedBy = &keyID
p.UserVerified = true
}
p.SubmittedAt = &now
})
if err != nil {
if errors.Is(err, place.ErrPlaceNotFound) {
return apiv1.PatchPlaceAccessibility404JSONResponse{Error: "place not found"}, nil
}
if errors.Is(err, place.ErrInvalidPatch) {
return apiv1.PatchPlaceAccessibility400JSONResponse(validationError([]validation.FieldError{{Field: "body", Reason: err.Error()}})), nil
}
return nil, err
}

auditAction := "update"
if created {
auditAction = "create"
}
audit.Log(s.db, "accessibility_profiles", input.ID, keyID, auditAction)
audit.Log(s.db, "accessibility_profiles", profile.ID, keyID, auditAction)

return apiv1.PatchPlaceAccessibility200JSONResponse(input), nil
return apiv1.PatchPlaceAccessibility200JSONResponse(profile), nil
}

func (s *Server) handleHealthz(w http.ResponseWriter, r *http.Request) {
Expand Down
4 changes: 2 additions & 2 deletions cmd/api/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func handlerForServer(t *testing.T, srv *Server) http.Handler {
BaseURL: "/v1",
BaseRouter: v1Mux,
ErrorHandlerFunc: srv.validationErrorHandler,
Middlewares: []apiv1.MiddlewareFunc{bodySizeLimiter(1 << 20)},
Middlewares: []apiv1.MiddlewareFunc{captureRawBody, bodySizeLimiter(1 << 20)},
})

v1Handler := nethttp_middleware.OapiRequestValidatorWithOptions(swagger, &nethttp_middleware.Options{
Expand Down Expand Up @@ -85,7 +85,7 @@ func handlerNoAuth(t *testing.T, srv *Server) http.Handler {
BaseURL: "/v1",
BaseRouter: v1Mux,
ErrorHandlerFunc: srv.validationErrorHandler,
Middlewares: []apiv1.MiddlewareFunc{bodySizeLimiter(1 << 20)},
Middlewares: []apiv1.MiddlewareFunc{captureRawBody, bodySizeLimiter(1 << 20)},
})

v1Handler := nethttp_middleware.OapiRequestValidatorWithOptions(swagger, &nethttp_middleware.Options{
Expand Down
6 changes: 2 additions & 4 deletions cmd/ingestion/main_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,6 @@ func TestRunCanonical_DoesNotOverwriteUserVerified(t *testing.T) {
ctx := context.Background()
db := testDB

isLevel := false
repo := place.NewRepository(db)
seed := models.Place{
OSMID: 2001, OSMType: models.OSMNode, Name: "Verified",
Expand All @@ -292,9 +291,8 @@ func TestRunCanonical_DoesNotOverwriteUserVerified(t *testing.T) {
if err := db.Create(&seed).Error; err != nil {
t.Fatalf("seed place: %v", err)
}
_, err := repo.UpsertProfile(ctx, seed.ID, &models.AccessibilityProfile{
Entrance: &models.EntranceProps{IsLevel: &isLevel},
UserVerified: true,
_, _, err := repo.UpsertProfile(ctx, seed.ID, []byte(`{"entrance":{"is_level":false}}`), func(p *models.AccessibilityProfile) {
p.UserVerified = true
})
if err != nil {
t.Fatalf("seed profile: %v", err)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/InWheelOrg/inwheel-api
go 1.26.4

require (
github.com/evanphx/json-patch/v5 v5.9.11
github.com/getkin/kin-openapi v0.145.0
github.com/golang-migrate/migrate/v4 v4.19.1
github.com/google/uuid v1.6.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=
github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU=
github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/getkin/kin-openapi v0.145.0 h1:htBX+Q7SevVaCUqymFegUKzH2WCbewl9tsmyn2FMGWY=
Expand Down
Loading
Loading