Skip to content

Implement S3 media storage, event management, and API improvements - #279

Draft
amit0539 wants to merge 146 commits into
mainfrom
dev
Draft

amit0539 wants to merge 146 commits into
mainfrom
dev

Conversation

@amit0539

@amit0539 amit0539 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Pull Request

Description

Brief description of the changes introduced by this PR.

Type of Change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Performance improvement
  • Code refactoring
  • Test improvements

Related Issues

Fixes #(issue number)
Closes #(issue number)
Relates to #(issue number)

Changes Made

  • Change 1
  • Change 2
  • Change 3

Testing

  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have tested this change manually

Test Instructions

Please describe how reviewers can test your changes:

  1. Step 1
  2. Step 2
  3. Step 3

Screenshots (if applicable)

Add screenshots to help explain your changes.

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules
  • I have run black ., isort ., and flake8 and fixed any issues
  • Database migrations are included (if applicable)

Additional Notes

Add any additional notes or context about the PR here.

saqibmanan and others added 30 commits October 9, 2026 19:07
A green 'Tests skipped' job records it on the run, and Finalize Deploy
still prunes images. main ignores the flag.
Run workflow on dev with 'rollback' ticked skips the build and runs the
existing rollback job, which restores the previously live image. The run
stays green when the rollback succeeds.
ci(deploy): SKIP_DEV_TESTS flag and a dev rollback button
The fallback https://api.civicdataspace.in does not resolve, so every
download_url in DCAT/Croissant/Dublin Core exports was a dead link when
PUBLIC_API_URL was unset. Use https://api.datakeep.civicdays.in, the prod
API host, in settings, the export adapter and .env.example.

Closes #238
fix(api): point PUBLIC_API_URL fallback at the live prod API
The export view caught every ValueError around export_dataset() and sent
str(exc) back with a 400, so internal errors (crosswalk, dates, rdflib)
reached anonymous users verbatim and were reported as client errors.

Validate standard and format against export_options() before exporting
and answer with a fixed message plus the options. Every other failure
now falls to the logged generic 500.

Closes #240
fix(api): stop returning exception text from metadata export
DVC never worked: uploaded files were never under DVC_REPO_PATH, so every
DVC call raised and createMajorVersion always failed. Remove the manager,
the setup command, version-change detection and the post_save signal.

createMajorVersion now writes the ResourceVersion row directly inside
transaction.atomic(), behind IsAuthenticated plus a check that the caller
owns the dataset or may change it.

BREAKING CHANGE: the setup_dvc management command and DVC_* settings are gone.
Media moves to S3 only, through django-storages. Two storages share one
bucket under <STORAGE_ENV>/public and <STORAGE_ENV>/private: public assets
get unsigned, cacheable URLs; private files get 5-minute presigned URLs.
The default storage is private, so anything that falls back to it is never
world-readable by accident. Empty access keys use the boto3 credential
chain (ECS/EC2 task role).

boto/urllib3 loggers are capped at WARNING because at DEBUG they log every
signed request, Authorization header included.

Tests swap all storages for InMemoryStorage and never reach S3.
Every FileField/ImageField now names a storage: logos, cover images,
profile pictures and publication block files go to public storage;
resource files and chart images go to private storage. The storages are
callables, so the migrations record a function reference, not bucket
settings.

upload_to paths drop their "files/public/" and "files/" prefixes, which
only repeated what MEDIA_ROOT used to add; the storages already put every
key under <env>/public or <env>/private.
S3 has no FieldFile.path, so every reader that used it would raise
NotImplementedError once media left local disk.

- local_copy() yields a temporary local copy (keeping the extension) for
  pandas, libmagic and the YAML/XML parsers; data indexing, entry counts
  and MIME validation use it.
- The lru_cache on the loaders is dropped: it keyed on temp paths that
  are deleted on exit, so it only held DataFrames in memory.
- Downloads stream with FileResponse instead of reading whole objects.
- Charts only check that the file exists; they read the indexed table.
- Search documents index the storage URL instead of a rewritten disk path.
Links issued before the move pointed at /public/<name> on disk. That route
now redirects to the file's public S3 URL, after stripping the old
"files/public/" or "files/" prefix from the name.

Only public files redirect. The old static() route also served resources
and drafts whenever DEBUG was on; anything outside public storage, or a
name that tries to traverse paths, is a 404 here.
Rows created on disk carry a "files/public/" or "files/" prefix that the
S3 keys no longer use. For each stored name the command puts the file at
the normalised key in the storage its field names, taken from the old S3
key or, with --source, from the old disk tree, then repoints the row.

Dry run by default; --execute copies and renames. Safe to re-run (names
already in place are skipped) and deletes nothing.
Regression tests for the local-disk/DVC to S3 migration: S3 storage
options (unsigned public URLs, 5-minute presigned private URLs, private
default), which storage each file field names, local_copy() and MIME
checks on storage without paths, prefix-free upload names, the legacy
/public redirect (public files only, no traversal), createMajorVersion's
owner-only version write, and migrate_media_to_s3 (dry run, disk and old
S3 sources, missing files, failed copies).
Replace the DVC references in SECURITY.md and AGENTS.md with the S3
storage layout and access rules, and add the no-co-author commit rule to
AGENTS.md.
Agents kept tripping over setup the file never mentioned (.env and logs/
are needed before tests boot; pre-commit pins python3.11) and over
S3-era rules that lived only in code review. Add a quick start, a
commands table with the SDK test command, task checklists for mutations,
model changes and bug fixes, a files-and-media section (no FieldFile.path,
local_copy, FileResponse, public vs private storage), and git safety
rules (self-contained commits, no AI co-author trailer, never stash the
user's work). Existing rules are unchanged.
CivicDataLab's scrapers fill "Source identifier" on every dataset they upload
(dataspace-scrapers/<scraper_id>/<dataset_key>) and read it back to recognise their
own datasets, so a dataset is never created twice and their upload records can be
rebuilt from DataSpace. The data migration creates the item, or switches it back on
if an admin switched it off; reversing it deletes nothing.

Tests: tests/test_source_identifier_migration.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fier

feat(metadata): add source identifier dataset metadata item
…blications

Add useCasesTable, collaborativesTable, aiModelsTable and publicationsTable,
shaped like datasetsTable: client filters and sort options limited to an
allowlist per module, limit/offset paging, the total after filters, and
counts per status for the dashboard tabs (ignoring the status filter so tab
labels stay stable).

Each query shows the same rows as the module's existing list query, plus
published (for AI models: public and active) rows when includePublic is
set. The existing list queries are unchanged. StatusCount and
status_counts() are shared in api/utils/qs_utils.py. No migration.
The tab counts in datasetsTable were an inline copy of what
status_counts() in api/utils/qs_utils.py now does for the other four
tables. Call the helper instead, so all five tables count statuses in one
place. status_counts() takes an optional item_type so the dataset table
keeps its DatasetStatusCount type; the GraphQL schema is unchanged.
feat(api): table queries for use cases, collaboratives, AI models, publications
The charts dashboard loads every built chart and chart image through
getChartData and searches them in the browser. chartsTable returns one
page of both kinds in a single list, with the total count and per-status
counts, using the shared table helpers.

Both tables are merged in one SQL UNION, so counting, sorting and slicing
happen in the database; only the rows of the page are then loaded.
Visibility and permission are the same as getChartData. Rows keep their
types (TypeResourceChart, TypeResourceChartImage), so existing fragments
work unchanged. getChartData is untouched.
Sorting and paging now go through the same helper as the other table
queries. Only filtering stays per table, because Django cannot filter
after a UNION. Drops the extra id tie-breaker, matching the others.
feat(api): add chartsTable with filters, sorting and pagination
This commit introduces a new Event model with fields for name, location, dates, and status, along with a corresponding GraphQL schema for creating, updating, and querying events. The schema includes input types for event creation and updates, as well as queries for retrieving events based on various filters. Additionally, utility functions for handling Luma embeds and event permissions are implemented to ensure proper validation and access control.
An event whose owner was deleted (user set to NULL) and has no
organization was reported as individual by the API but not by
Event.is_individual_event. Use the same check in both.
Each event gets a 12-character public_id; its link is the name words
plus that id (urlSlug), so renames never break links and two events
can share a name. eventBySlug finds the event by the id at the end of
the link. The slug is no longer unique and the counter loop is gone.

Also drops the 0055_event dependency on
0049_merge_publication_and_accessmodel, which does not exist.
Chart mutations save without full_clean, so the 50-character name and
1000-character description limits were only enforced by Postgres, whose
own error text ("value too long for type character varying(50)") reached
the client. Names were only checked for truthiness, so "   " was saved.

Chart and chart image create/edit now trim names and descriptions and
check them before anything is saved: too long values get a fixed
message, and a blank name is refused when it would replace a saved one.
A chart that is already blank can still be sent back as it is, because
the chart editor resends the current name with every other change.

Fixes #325
anantjain341 and others added 25 commits November 25, 2026 15:47
Publication search documents have no tags field, but the unified
search result serializer requires it, so any page holding a
publication failed with a 500. Publication hits now get an empty
tags list, like events already do.
…ions

fix(search): return publications in unified search
fix(api): refuse blank and too long chart names with a clear message
The collaborative search handler (api/signals/collaborative_signals.py)
was never imported in api/signals/__init__.py, so it never ran. The
search library only indexes published collaboratives on save and never
removes one that goes back to draft, so unpublished collaboratives
stayed in the public listing and linked to a page that answers "does
not exist". Publishing and unpublishing also did not refresh the search
cache.

Register the handler like the dataset, use case and AI model ones. A
new test starts Django in a fresh process and checks that every module
in api/signals/ is loaded, since another test imports this one directly
and hid the gap in CI.

Fixes #326
All media is stored on S3 now, so file and image fields have no
location on the server's disk. strawberry-django's file types still
exposed path, which asked for one and could only fail with "This
backend doesn't support absolute paths", nulling the whole file object.

Register types with the same names and all other fields, without
path: name is the storage key and url opens the file.

Fixes #284
The publication wizard picks real platform users but the backend only
stored their display names in `authors`, so the frontend rebuilt fake
ids from names on reload and the same person could be added twice
(CivicDataLab/DataSpaceFrontend#560).

Publications now have a `contributors` many-to-many to users, like use
cases. Create and update take `contributorIds`; sending them replaces
the contributors and clears the old names (null keeps, an empty list
clears). Publishing accepts a contributor or an old saved name, and the
error stays keyed `authors` because the smoke tests check that key.
Contributor emails are hidden from people who cannot edit the
publication.

Migration 0068 links the names already saved to users: a repeated name
links once, a name shared by several users goes to the owner or a
single organisation member and is otherwise left unlinked, and names
matching nobody are ignored. `authors` is left untouched so a rolled
back deploy still works, and only counts are printed because deploy
logs are public. `manage.py unlinked_publication_authors` lists the
names that did not link, for checking before `authors` is removed.
Publication mutations save without full_clean and the service only ran
URLValidator(), whose default schemes include ftp/ftps. Nothing limited
the date, description, title, link length or number of people, so the
API stored values the wizard never sends, and a title over 300 or a
link over 200 characters failed in Postgres instead of returning a
message (#327).

Links must now be http or https and fit their column, titles fit
theirs, descriptions are at most 1000 characters (as datasets,
organisations and charts), dates cannot be in the future (as the
dataset form; one day of slack because the server runs in UTC), and a
publication has at most 50 contributors or authors. Drafts are checked
on what was sent; publishing and edits to a published publication
check every stored value.
The slug is made from the name on every save and must be unique, but
createOrganization and updateOrganization never checked it, so a name
like "CivicDataLab" next to an existing civicdatalab returned the
database's own duplicate key error. Both mutations now check the slug
first and refuse with a fixed message; a request that takes the slug in
between gets the same message. Creating an organization and making the
caller its admin now happen in one transaction.

Names with no letters or digits give an empty slug, which cannot work
as a link, so they are refused too. Slugs are cut to the 75-character
column, so long names no longer fail on Postgres.

Fixes #288
…publish

fix(search): remove unpublished collaboratives from search
fix(api): remove path from GraphQL file fields
fix(api): refuse organization names whose slug is taken
feat(api): link publication contributors to users
fix(api): keep publication fields to the platform's limits
assignOrganizationRole only checked that the caller's role could edit
content, so an editor could give the admin role to anyone, themselves
included. It now uses the same admin check as adding and removing
members, and refuses a change to the caller's own role (ids compared as
numbers, so a padded id cannot get round it).
…nd dataspaces

The sector, SDG, metadata field and dataspace create/update/delete
mutations had no permission check (deleteMetadata only asked for
sign-in), so anyone could add, rename or delete the records every
organisation's datasets, use cases and filters use. They now require a
signed-in superuser, through a new IsSuperuser permission; so do
deleteTag and deleteTags, which any signed-in user could call.
Chart reads only checked whether the caller may see the dataset. A
published dataset is public, so getChartData (the dataset page's
Visualisations tab) and the other chart queries returned its draft and
unpublished charts and chart images to anyone; unpublishing a chart
withdrew nothing.

Published charts of datasets the caller may see stay public. Draft and
unpublished charts are now shown only to people with a grant on the
dataset: owner, organisation members whose role can view, dataset
permissions, editors and superusers. The dataset search flag has_charts
now counts published charts only.
The user type is returned by user(), userById, getPublishers and the
creator and contributors of every published dataset, use case,
collaborative and publication, and it carried the email address, last
login and organisation memberships to anyone. User ids are sequential
and login names are often email addresses, so every address could be
collected without signing in.

Email, an email-shaped login name and last login are now shown only to
the user, superusers and members of a shared organisation whose role
can view it; fullName no longer falls back to an email address, and
memberships list only organisations the caller may list. user(id |
username) answers only for the caller's own account (superusers: any).
The public publisher and unified search results no longer carry users'
email addresses or email-shaped login names, the publisher search no
longer matches on them, and the user search document stops storing them.
searchUsers matches a login name that is an email address only as a whole
and returns at most 20 people, and the public metadata export and AI
model detail no longer fall back to the login name for unnamed users.
Name, picture, bio, links and location stay public.
fix(auth): only organisation admins can change member roles
…ruser

fix(api): only superusers can change sectors, SDGs, metadata fields and dataspaces
fix(api): hide draft and unpublished charts of published datasets
…elds

fix(auth): keep users' email and login details private
deleteOrganization compared the membership's role (a Role row) with the
string "admin", which is never equal, so everyone except superusers was
refused, including the organization's own admins. Compare the role name.
fix(api): let organization admins delete their organization
Every authenticated request copied given_name/family_name from the
Keycloak token onto the user. A token keeps the name it was issued with,
so the next request made with a token from before a profile edit put the
old name back (on dev, a single REST request after updateUser did it).

Take names from Keycloak only while ours are empty; email, username and
admin flags still sync on every request.
fix(auth): keep profile name edits when an older token signs in

This branch was successfully deployed

1 active deployment
development — fdceb569 Deployed Dec 1, 2026 by anantjain341 via Finalize Deploy #135
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants