Skip to content

Bug: csapiCollections (and 5 sibling collection getters) crash with TypeError when landing page omits 'data' rel link (e.g. OpenSensorHub) #188

Closed

Description

@nsnarayanam

Summary

OgcApiEndpoint.csapiCollections crashes with TypeError: Cannot read properties of null (reading 'collections') when the endpoint's landing page does not advertise a link with rel: "data" (or its long-URI variant). Five sibling collection getters share the same bug pattern.

The crash is triggered by a real, conformant CSAPI server: the OpenSensorHub demo (http://45.55.99.236:8080/sensorhub/api) cited in PR #136's own validation list.

Reproduction

import { OgcApiEndpoint } from '@camptocamp/ogc-client';

const endpoint = new OgcApiEndpoint('http://45.55.99.236:8080/sensorhub/api');
console.log(await endpoint.hasConnectedSystems);  // true (correct)
console.log(await endpoint.csapiCollections);     // ❌ throws

Stack trace:

TypeError: Cannot read properties of null (reading 'collections')
    at parseCollections (dist/dist-node.js:2873:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:104:5)

Root cause

Two interacting issues:

1. csapiCollections doesn't null-check data (the immediate crash)

src/ogc-api/endpoint.ts:230-236:

get csapiCollections(): Promise<string[]> {
  return Promise.all([this.data, this.hasConnectedSystems])
    .then(([data, hasCSAPI]) => (hasCSAPI ? data : { collections: [] }))
    .then(parseCollections)   // ← parseCollections(null) throws
    ...

Compare to the sibling allCollections, which correctly null-checks before calling parseCollections:

return this.data.then((dataDocument) =>
  dataDocument ? parseCollections(dataDocument) : []
);

The same null-deref pattern is present in 5 other getters sharing the Promise.all([this.data, this.hasX]).then(...).then(parseCollections) shape:

Line Getter
187 recordCollections
198 featureCollections
206 edrCollections
244 vectorTileCollections
257 mapTileCollections

2. Why data is null here (separate concern, broader fix)

collectionsUrl only follows links with rel: "data" or http://www.opengis.net/def/rel/ogc/1.0/data. OpenSensorHub's landing page uses rel: "collections" instead:

{
  "rel": "collections",
  "title": "Collections available on this server",
  "href": "http://45.55.99.236:8080/sensorhub/api/collections",
  "type": "application/json"
}

So collectionsUrl resolves to null, data resolves to null, and every dependent getter then crashes.

OGC API Common Part 2 specifies data as the canonical rel — OpenSensorHub is technically out of spec — but rel: "collections" is widely seen in the wild, and after the immediate null-deref is fixed, the library still won't discover any collections from these servers. Worth considering whether collectionsUrl should additionally accept rel: "collections" for compatibility.

Proposed fix

Minimum (unblocks the crash, no behavior change)

Mirror the allCollections null-guard in all six affected getters. Single-token edit per getter:

-    .then(([data, hasCSAPI]) => (hasCSAPI ? data : { collections: [] }))
+    .then(([data, hasCSAPI]) => (hasCSAPI && data ? data : { collections: [] }))

I've applied this to csapiCollections locally and verified the OpenSensorHub case now returns { hasConnectedSystems: true, collections: [] } cleanly (instead of crashing). The same diff applied to the other 5 getters would make them robust by symmetry.

Recommended (also fixes the empty-collections downstream issue)

Additionally, accept rel: "collections" in collectionsUrl:

-    ['data', 'http://www.opengis.net/def/rel/ogc/1.0/data'],
+    ['data', 'http://www.opengis.net/def/rel/ogc/1.0/data', 'collections'],

This is a pragmatic compatibility win for OpenSensorHub-style servers; happy to defer to maintainers on whether this belongs here vs. being treated as a server-conformance issue.

Why this matters / context

I'm building a Python ADK agent (Google Gemini) that uses @camptocamp/ogc-client/csapi via a Node CLI subprocess to query CSAPI endpoints from natural language. This is the second consumer of the library beyond ogc-csapi-explorer, so the bug surfaced immediately when probing the public test servers cited in PR #136.

Cross-references:

Environment

  • Node v24.15.0, npm 11.12.1
  • Snapshot: OS4CSAPI/ogc-client-CSAPI_2 phase-7 branch
  • Built locally with npm run build
  • Probed against OpenSensorHub on 2026-05-03

Narasimha Sharma Narayanam (@nsnarayanam )

Activity

  1. nsnarayanam commented on May 3, 2026

    @nsnarayanam
    Author

    After patching csapiCollections locally and continuing to probe OpenSensorHub, two related issues blocked further library use. Both involve the library's strictness vs. real-world server shape. Filing as a follow-up here rather than separate issues since they're discovered in the same session and share the same reproducer.

    Issue 3: parseCollections ignores featureType-based CSAPI signaling

    src/ogc-api/info.ts:294-301 flags a collection as hasConnectedSystems: true only when its links include a rel matching ^ogc-cs:.+$:

    if (
      Array.isArray(collection.links) &&
      collection.links.some(
        (link) => typeof link.rel === 'string' && /^ogc-cs:.+$/.test(link.rel)
      )
    ) {
      result.hasConnectedSystems = true;
    }

    OpenSensorHub doesn't put ogc-cs:* rels on its collections — it signals the resource family at the collection level via featureType:

    {
      "id": "all_systems",
      "itemType": "feature",
      "featureType": "system",          // ← this is the CSAPI signal
      "links": [
        { "rel": "self", "href": "..." },
        { "rel": "items", "href": "systems" }
      ]
    }

    Result: csapiCollections returns [] against an OpenSensorHub server that clearly serves CSAPI (its conformance doc declares ogcapi-connectedsystems-1/1.0/conf/core and the root advertises rel: "systems", rel: "datastreams" etc.).

    Possible fix: also accept collection.featureType in {system, datastream, datastreams, observation, observations, samplingFeature, featuresOfInterest, procedure, deployment} as a CSAPI signal:

    + const CSAPI_FEATURE_TYPES = new Set([
    +   'system', 'datastream', 'datastreams',
    +   'observation', 'observations',
    +   'samplingFeature', 'featureOfInterest',
    +   'procedure', 'deployment',
    + ]);
    +
      if (
        Array.isArray(collection.links) &&
        collection.links.some(
          (link) => typeof link.rel === 'string' && /^ogc-cs:.+$/.test(link.rel)
    -   )
    +   ) ||
    +   (typeof collection.featureType === 'string' &&
    +    CSAPI_FEATURE_TYPES.has(collection.featureType))
      ) {
        result.hasConnectedSystems = true;
      }

    I recognize this is a judgement call about how generously the library should map server-side conventions. Open to deferring it as a server-conformance issue if you'd prefer servers to advertise ogc-cs: rels on their collections.

    Issue 4: getCollectionDocument follows self link blindly without validating the result

    src/ogc-api/endpoint.ts:359-377:

    public getCollectionDocument(collectionId: string): Promise<OgcApiDocument> {
      return Promise.all([this.allCollections, this.data])
        .then(([collections, data]) => { /* find collection */ })
        .then(async (collection) => {
          if (hasLinks(collection, ['self'])) {
            return fetchLink(collection, 'self', this.baseUrl);  // ← trusts self blindly
          }
          return fetchDocument(getChildPath(await this.collectionsUrl, collectionId));
        });
    }

    OpenSensorHub returns malformed self links on collection items — they point to the parent /collections URL instead of the per-collection URL:

    {
      "id": "all_systems",
      "links": [
        { "rel": "self", "href": "http://45.55.99.236:8080/sensorhub/api/collections" }
      ]
    }

    So getCollectionDocument('all_systems') returns the parent {collections: [...], links: [...]} document. Then createCSAPIBuilder correctly rejects it:

    EndpointError: Collection 'all_systems' document is not a valid OgcApiCollectionInfo
        at createCSAPIBuilder (.../csapi/factory.js:16:11)
    

    The server is plainly wrong here. But the library has enough information to detect the mismatch and fall back to URL construction (the existing else branch already does this). A simple post-fetch validation:

    .then(async (collection) => {
      if (hasLinks(collection, ['self'])) {
    -   return fetchLink(collection, 'self', this.baseUrl);
    +   const fetched = await fetchLink(collection, 'self', this.baseUrl);
    +   // If the self link returned a doc whose id doesn't match what we asked for,
    +   // fall through to URL construction (defensive against bad server self links).
    +   if (fetched && typeof fetched.id === 'string' && fetched.id === collectionId) {
    +     return fetched;
    +   }
      }
      return fetchDocument(getChildPath(await this.collectionsUrl, collectionId));
    });

    Trades zero behavior change for conformant servers against graceful degradation for non-conformant ones. Happy to PR if accepted.

    Summary table (running tally for OpenSensorHub interop)

    # Where Layer Status
    1 csapiCollections null-deref Library bug Original report above
    2 collectionsUrl rejects rel: "collections" Library compatibility Mentioned in original report
    3 parseCollections ignores featureType Library / convention mismatch This comment
    4 getCollectionDocument blind self-link follow Server bug + library could be defensive This comment

    Net: against this one publicly-cited test server, four distinct fixes are needed end-to-end before createCSAPIBuilder('weather-stations') succeeds. Two of those are server-side bugs (OpenSensorHub maintainers should know), but in all four cases the library could be more permissive without weakening its correctness.

    I've worked around all four locally and can confirm createCSAPIBuilder then succeeds against OpenSensorHub end-to-end. For ongoing agent development I'm switching to a local conformant mock to remove the moving parts; happy to share that mock if it'd be useful as a CI fixture.

    — Narasimha Sharma Narayanam (@nsnarayanam)

  2. nsnarayanam commented on May 3, 2026

    @nsnarayanam
    Author

    Follow-up: repo for the second-consumer agent that surfaced these bugs: https://github.com/nsnarayanam/ogc-csapi-agent

  3. Sam-Bolling commented on May 3, 2026

    @Sam-Bolling

    Greetings, @nsnarayanam, thank you for your interest in the CSAPI client library work and identifying these issues. I will work on them as time permits. I also added your repository to the repositories of interest for the OGC CSAPI SWG's participation guide in the OGC's upcoming code sprint on 11-13MAY2026. The participation guide is here if you are interested and available to join us: https://os4csapi.github.io/code-sprint-guide/builder-days-2026/.

    Respectfully,
    Sam

  4. nsnarayanam commented on May 4, 2026

    @nsnarayanam
    Author
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions