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
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- **Secret Sharing Foundation (Phase 3)** (#182)
- New `secret_shares` table for fine-grained access control
- XOR constraint enforces sharing with either user OR role (not both)
- Permission hierarchy: `admin` > `write` > `read`
- Optional expiration support via `expires_at` timestamp
- `SecretShare` model with UUID primary key, relationships, and scopes
- `Secret.shares()` relationship for access control queries
- `Secret.userHasPermission()` method validates user permissions (owner OR share)
- `active()` scope filters non-expired shares
- Migration tests verify schema integrity (3 tests)
- Model tests cover relationships, scopes, and expiration logic (10 tests)
- Foundation for upcoming Controllers and Policies in separate PR

- **File Attachments API (Phase 2)** (#175)
- Upload encrypted file attachments to secrets (POST `/v1/secrets/{secret}/attachments`)
- List attachments for a secret (GET `/v1/secrets/{secret}/attachments`)
Expand Down
49 changes: 49 additions & 0 deletions app/Models/Secret.php
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,16 @@ public function attachments(): \Illuminate\Database\Eloquent\Relations\HasMany
return $this->hasMany(SecretAttachment::class);
}

/**
* Relation to SecretShare (access control).
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany<SecretShare, $this>
*/
public function shares(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(SecretShare::class);
}

/**
* Get count of attachments for this secret.
*
Expand Down Expand Up @@ -320,4 +330,43 @@ public function scopeActive($query)
->orWhere('expires_at', '>', now());
});
}

/**
* Check if user has specific permission on this secret.
*
* Permission hierarchy: admin > write > read
*
* @param string $permission One of: read, write, admin
*/
public function userHasPermission(User $user, string $permission): bool
{
// Owner always has full access
if ($this->owner_id === $user->id) {
return true;
}

// Check active shares
$share = $this->shares()
->where(function ($q) use ($user) {
$q->where('user_id', $user->id)
->orWhereIn('role_id', $user->roles->pluck('id'));
})
->where(function ($q) {
$q->whereNull('expires_at')
->orWhere('expires_at', '>', now());
})
->first();

if (! $share) {
return false;
}

// Permission hierarchy: admin > write > read
return match ($permission) {
'read' => in_array($share->permission, ['read', 'write', 'admin']),
'write' => in_array($share->permission, ['write', 'admin']),
'admin' => $share->permission === 'admin',
default => false,
};
}
}
137 changes: 137 additions & 0 deletions app/Models/SecretShare.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
<?php

// SPDX-FileCopyrightText: 2025 SecPal Contributors
//
// SPDX-License-Identifier: AGPL-3.0-or-later

namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\Permission\Models\Role;

/**
* SecretShare model for managing access control to secrets.
*
* A share grants read/write/admin permission to either a user OR a role.
* XOR constraint enforced at database level.
*
* @property string $id UUID primary key
* @property string $secret_id UUID foreign key to secrets
* @property ?string $user_id UUID foreign key to users (XOR with role_id)
* @property ?int $role_id Foreign key to roles (XOR with user_id)
* @property string $permission Enum: read|write|admin
* @property string $granted_by UUID foreign key to users (who granted)
* @property \Illuminate\Support\Carbon $granted_at When share was granted
* @property ?\Illuminate\Support\Carbon $expires_at Optional expiration
* @property \Illuminate\Support\Carbon $created_at
* @property \Illuminate\Support\Carbon $updated_at
* @property-read Secret $secret
* @property-read ?User $user
* @property-read ?Role $role
* @property-read User $granter
* @property-read bool $is_expired
*/
class SecretShare extends Model
{
use HasUuids;

/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'secret_shares';

/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'secret_id',
'user_id',
'role_id',
'permission',
'granted_by',
'granted_at',
'expires_at',
];

/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'granted_at' => 'datetime',
'expires_at' => 'datetime',
];

/**
* Get the secret that this share grants access to.
*
* @return BelongsTo<Secret, $this>
*/
public function secret(): BelongsTo
{
return $this->belongsTo(Secret::class);
}

/**
* Get the user that has access (if user-based share).
*
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}

/**
* Get the role that has access (if role-based share).
*
* @return BelongsTo<Role, $this>
*/
public function role(): BelongsTo
{
return $this->belongsTo(Role::class);
}

/**
* Get the user who granted this share.
*
* @return BelongsTo<User, $this>
*/
public function granter(): BelongsTo
{
return $this->belongsTo(User::class, 'granted_by');
}

/**
* Scope to only active (non-expired) shares.
*
* @param \Illuminate\Database\Eloquent\Builder<SecretShare> $query
* @return \Illuminate\Database\Eloquent\Builder<SecretShare>
*/
public function scopeActive(\Illuminate\Database\Eloquent\Builder $query)
{
return $query->where(function ($q) {
$q->whereNull('expires_at')
->orWhere('expires_at', '>', now());
});
}

/**
* Check if this share has expired.
*/
public function getIsExpiredAttribute(): bool
{
if ($this->expires_at === null) {
return false;
}

return $this->expires_at->isPast();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

// SPDX-FileCopyrightText: 2025 SecPal Contributors
//
// SPDX-License-Identifier: AGPL-3.0-or-later

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*
* Creates the secret_shares table for managing access control to secrets.
* A share grants read/write/admin permission to a user or role.
*/
public function up(): void
{
Schema::create('secret_shares', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('secret_id')->constrained('secrets')->onDelete('cascade');
$table->foreignUuid('user_id')->nullable()->constrained('users')->onDelete('cascade');
$table->foreignId('role_id')->nullable()->constrained('roles')->onDelete('cascade');
$table->enum('permission', ['read', 'write', 'admin']);
$table->foreignUuid('granted_by')->constrained('users');
$table->timestamp('granted_at');
$table->timestamp('expires_at')->nullable();
$table->timestamps();

// Indexes
$table->index('secret_id');
$table->index('user_id');
$table->index('role_id');
$table->index('expires_at');

// Unique constraints: One share per secret+user or secret+role
$table->unique(['secret_id', 'user_id']);
$table->unique(['secret_id', 'role_id']);
});

// Add CHECK constraint: Either user_id OR role_id must be set, not both
DB::statement('ALTER TABLE secret_shares ADD CONSTRAINT secret_shares_user_xor_role CHECK ((user_id IS NOT NULL AND role_id IS NULL) OR (user_id IS NULL AND role_id IS NOT NULL))');
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('secret_shares');
}
};
58 changes: 58 additions & 0 deletions tests/Feature/Migrations/CreateSecretSharesTableTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

// SPDX-FileCopyrightText: 2025 SecPal Contributors
//
// SPDX-License-Identifier: AGPL-3.0-or-later

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Schema;

uses(RefreshDatabase::class);

describe('CreateSecretSharesTable Migration', function () {
test('creates secret_shares table with correct columns', function (): void {
expect(Schema::hasTable('secret_shares'))->toBeTrue();

expect(Schema::hasColumn('secret_shares', 'id'))->toBeTrue();
expect(Schema::hasColumn('secret_shares', 'secret_id'))->toBeTrue();
expect(Schema::hasColumn('secret_shares', 'user_id'))->toBeTrue();
expect(Schema::hasColumn('secret_shares', 'role_id'))->toBeTrue();
expect(Schema::hasColumn('secret_shares', 'permission'))->toBeTrue();
expect(Schema::hasColumn('secret_shares', 'granted_by'))->toBeTrue();
expect(Schema::hasColumn('secret_shares', 'granted_at'))->toBeTrue();
expect(Schema::hasColumn('secret_shares', 'expires_at'))->toBeTrue();
expect(Schema::hasColumn('secret_shares', 'created_at'))->toBeTrue();
expect(Schema::hasColumn('secret_shares', 'updated_at'))->toBeTrue();
});

test('has indexes on key columns', function (): void {
$indexes = Schema::getIndexes('secret_shares');
$indexColumns = collect($indexes)->pluck('columns')->flatten()->toArray();

expect($indexColumns)->toContain('secret_id');
expect($indexColumns)->toContain('user_id');
expect($indexColumns)->toContain('role_id');
expect($indexColumns)->toContain('expires_at');
});

test('has unique constraints for secret_id with user_id and role_id', function (): void {
$indexes = Schema::getIndexes('secret_shares');

// Check for unique constraint on secret_id + user_id
$hasUserUnique = collect($indexes)->contains(function ($index) {
return $index['unique']
&& in_array('secret_id', $index['columns'])
&& in_array('user_id', $index['columns']);
});

// Check for unique constraint on secret_id + role_id
$hasRoleUnique = collect($indexes)->contains(function ($index) {
return $index['unique']
&& in_array('secret_id', $index['columns'])
&& in_array('role_id', $index['columns']);
});

expect($hasUserUnique)->toBeTrue();
expect($hasRoleUnique)->toBeTrue();
});
});
Loading