# Can They See This? - SharePoint Permissions Visualizer

A browser-based educational tool for visualizing and understanding SharePoint permissions inheritance, effective access calculation, and sharing link behavior.

## Overview

**Can They See This?** is a single-file, client-side web application that helps users understand how SharePoint permissions work. It simulates SharePoint's complex permission model including:
- Hierarchical permission inheritance (Site → Library → Folder → File)
- Breaking inheritance to create unique permissions
- Sharing links and their dangerous bypass behavior
- Effective permission calculation across multiple sources
- Risk assessment for permission configurations

## Key Features

### 1. Interactive Scenario Building
- Create realistic SharePoint hierarchies (Site → Library → Folder → File)
- Add users, groups, and external identities
- Toggle inheritance at any level
- View changes in real-time

### 2. Permissions Management
- Grant permissions to people and groups with various roles
- Create sharing links (Anyone, Organization, Specific, Existing)
- Set role assignments (None, Read, Contribute, Edit, Full Control)
- Manage direct assignments and inherited access

### 3. Effective Permissions Visualization
- Calculate who can see any item and why
- Show inheritance chain from root to selected item
- Identify dangerous permission configurations
- Highlight when sharing links bypass broken inheritance

### 4. Risk Assessment
- **High Risk**: "Anyone" sharing links, external users with Edit+, links bypassing unique permissions
- **Medium Risk**: Broken inheritance with many editors (5+)
- **Low Risk**: No obvious security issues detected

### 5. Export & Import
- Export scenarios as JSON for sharing
- Import scenarios from JSON files
- Export audit reports as CSV
- Save/load from browser localStorage

## Technology Stack

- **Pure HTML5/CSS3/JavaScript** - No frameworks or dependencies
- **Client-side only** - Runs entirely in the browser, no server required
- **Zero build process** - Just open the HTML file in a browser
- **Responsive design** - Works on desktop and mobile devices

## Quick Start

### Online Access

Visit **https://permissions.fyi** to use the tool immediately - no installation required!

### Local Development

1. **Open the file**: Simply open `index.html` in any modern web browser
2. **Load Sample**: Click "Load Sample" to see a pre-configured scenario
3. **Explore**: Select items in the middle panel to view and edit their permissions
4. **Experiment**: Toggle inheritance, add people, create sharing links
5. **Analyze**: View effective permissions and risk assessment in the right panel
6. **Export**: Generate a CSV audit report of all permissions

## Production Deployment

The application is currently deployed at **https://permissions.fyi**

### Web Server

- **Web Server**: Caddy v2.10.2
- **Port**: 3008 (behind Cloudflare tunnel)
- **Service**: `permissions-fyi-caddy` (systemd)

### Managing the Web Server

```bash
# Start the web server
sudo systemctl start permissions-fyi-caddy

# Stop the web server
sudo systemctl stop permissions-fyi-caddy

# Restart the web server
sudo systemctl restart permissions-fyi-caddy

# Check status
sudo systemctl status permissions-fyi-caddy

# View logs
sudo journalctl -u permissions-fyi-caddy -n 50
```

For detailed deployment instructions, troubleshooting, and operations guide, see **[DEPLOYMENT.md](DEPLOYMENT.md)**

### Security Features

The production deployment implements comprehensive security hardening:

- **HTTP Security Headers**: CSP, Permissions-Policy, Referrer-Policy, X-Frame-Options
- **Sensitive File Protection**: Blocks access to `.git`, `.env`, `.log`, backup files
- **Automatic Log Rotation**: 10MB rotation, keeps 5 files, 30-day retention
- **Geo-Restriction**: Australia-only access via Cloudflare WAF
- **DDoS Protection**: Cloudflare Bot Fight Mode and security controls
- **100% Client-Side**: No data sent to servers, runs entirely in browser

For complete security configuration details, see the Security Hardening section in **[DEPLOYMENT.md](DEPLOYMENT.md)**

## How It Works

### Data Model

The application maintains a simple state object:

```javascript
{
  principals: [
    {id, name, kind: 'user'|'group'|'external'|'link-virtual'}
  ],
  nodes: [
    {
      id,
      type: 'site'|'library'|'folder'|'file',
      name,
      parentId,
      inherits: boolean,
      assignments: [{principalId, role}],
      sharingLinks: [{id, type, role, created}]
    }
  ],
  selectedId,
  schemaVersion: 2
}
```

### Permission Calculation Algorithm

The effective permissions engine (`computeEffectiveDetailed()`) works in two phases:

**Phase 1: Direct Assignments (Respects Broken Inheritance)**
- Start at the selected item
- Walk up the tree collecting permission assignments
- Stop when hitting a node with `inherits: false`
- Track highest role for each principal across all sources

**Phase 2: Sharing Links (BYPASSES Broken Inheritance!)**
- Start at the selected item
- Walk ALL THE WAY to the root (critical security behavior)
- Collect all sharing links regardless of inheritance breaks
- Mark links that bypass unique permissions with warning flag
- Create virtual principals for each link type

This two-phase approach models the real SharePoint behavior where sharing links on parent folders can grant access to child items even when the child has unique permissions.

### Role Hierarchy

Permissions follow precedence order:
```
None < Read < Contribute < Edit < Full Control
```

When multiple sources grant access, the highest role wins.

### Sharing Link Types

1. **Anyone with the link** - Anonymous access, no sign-in required (HIGH RISK)
2. **People in your organization** - All authenticated company members
3. **Specific people** - Like direct assignment to named users
4. **People with existing access** - No new permissions, just a URL

## Architecture

### Code Organization

The 884-line HTML file is organized into logical sections:

```
Lines    Section                    Description
-----    -------                    -----------
1-111    HTML & CSS                 Document structure and dark theme
112-175  HTML Body                  Three-panel layout (Build, Structure, Effects)
176-884  JavaScript (IIFE)          All application logic
  178-198   Data Model              State structure and constants
  200-263   Core Logic              Permission calculation engine
  265-299   Risk Assessment         Security heuristics
  301-347   Sample Data             Pre-built realistic scenario
  349-761   UI Rendering            Builder, tree, and effects panels
  763-817   Import/Export           JSON/CSV, localStorage
  819-877   Utilities & Tests       Helper functions and self-test
  879-881   Initialization          Auto-load sample on start
```

### Key Functions

#### `computeEffectiveDetailed(node)` - Lines 214-263
The heart of the permission engine. Returns a map of `principalId -> {role, sources}` showing exactly who has access and why.

**Critical behavior**: Sharing links walk to root regardless of broken inheritance, modeling a dangerous but real SharePoint behavior.

#### `riskOf(node)` - Lines 265-299
Security heuristic that identifies:
- "Anyone" links (anonymous access)
- Links bypassing unique permissions
- External users with Edit+ access
- Broken inheritance with many editors

#### `renderBuilder()` - Lines 357-520
Left panel UI for editing selected item:
- Rename and toggle inheritance
- Add children/siblings with structural validation
- Grant permissions via direct assignment or sharing links
- Manage principals directory

#### `renderTree()` - Lines 665-684
Middle panel showing visual hierarchy with:
- Tree structure with connector lines
- Inheritance badges (inherits/unique)
- Sharing link indicators
- Click-to-select interaction

#### `renderEffects()` - Lines 687-761
Right panel displaying:
- Risk level with color-coded badge
- Inheritance chain visualization
- Detailed permission table with sources
- Explanations and warnings

## Sample Scenario

The included sample demonstrates realistic enterprise setup:

```
Contoso Marketing (Site)
├── All Company (Read)
├── Marketing Members (Edit)
├── Contoso Marketing Owners (Full Control)
├── Contoso Marketing Members (Edit)
├── Contoso Marketing Visitors (Read)
│
└── Documents (Library) - inherits
    ├── 🔗 "People in your organization" link (Read)
    │
    └── Campaigns (Folder) - UNIQUE PERMISSIONS
        ├── Bob Jenkins (Contribute)
        │
        └── Q4 Launch (Folder) - inherits from Campaigns
            ├── alice@vendor.example (Read) - external user
            ├── 🔗 "Anyone with the link" (Read) - ANONYMOUS!
            │
            └── Plan.docx (File) - inherits from Q4 Launch
```

### What This Demonstrates

1. **Inheritance Flow**: Site → Library inherits all permissions
2. **Breaking Inheritance**: Campaigns folder has unique permissions, blocking site-level access
3. **Sharing Links Bypass**: Despite Campaigns having unique permissions, the Documents library "Org" link still grants company-wide Read access to Plan.docx
4. **Anonymous Access**: Q4 Launch "Anyone" link allows public access to Plan.docx
5. **External Users**: Guest has Read access to Q4 Launch and everything under it

### Risk Analysis of Sample

The sample file `Plan.docx` has **HIGH RISK** because:
- Parent folder sharing links bypass the Campaigns folder's unique permissions
- "Anyone" link on Q4 Launch allows anonymous access
- External user has access to sensitive campaign data

## Critical SharePoint Behaviors Modeled

### 1. Inheritance Walkup
When inheritance is enabled, permissions flow down from parent to all children. Breaking inheritance stops this flow at that point.

### 2. Sharing Links Bypass Broken Inheritance
**This is the most dangerous SharePoint behavior!**

Even if a subfolder has unique permissions (broken inheritance), sharing links created on parent folders STILL grant access to items in that subfolder. This is "by design" but widely considered a security flaw.

Example:
```
Documents (Library)
├── 🔗 "Anyone" link (Read)
│
└── Confidential (Folder) - UNIQUE PERMISSIONS
    ├── Alice (Full Control) - only person with direct access
    │
    └── secrets.docx - ACCESSIBLE TO ANYONE via parent link!
```

The only way to block parent sharing links: Delete the parent's sharing link entirely.

### 3. Multiple Permission Sources
A user can gain access through:
- Direct assignment on the item
- Inheritance from parent (if not broken)
- Sharing links at any level (bypasses broken inheritance)
- Group membership (groups can be assigned permissions)

The highest role across all sources is the effective permission.

### 4. Role Precedence
If Bob has:
- Read from Site
- Contribute from Library
- Edit from a sharing link

Bob's effective permission is **Edit** (highest role wins).

## Use Cases

### For IT Admins
- Train new administrators on SharePoint permissions
- Demonstrate inheritance concepts
- Show the danger of "Anyone" sharing links
- Explain why items with unique permissions can still be accessed via parent links

### For Security Teams
- Assess risk in permission configurations
- Identify over-sharing patterns
- Document permission structures for audit
- Test permission scenarios before implementing in production

### For End Users
- Understand why they can/can't access items
- Learn how to safely share documents
- Visualize the impact of breaking inheritance
- See the risk of anonymous sharing links

### For Trainers
- Create realistic examples for training sessions
- Export scenarios to share with students
- Demonstrate before/after permission changes
- Show real-world misconfiguration risks

## Security Considerations

### What This Tool Does NOT Do
- Connect to real SharePoint sites
- Store data on servers
- Transmit any information over the network
- Require authentication or credentials
- Access any external resources

### Data Privacy
- All data stays in your browser
- localStorage only (optional, for convenience)
- No cookies, no tracking, no analytics
- Export files are generated client-side
- Safe to use with sensitive organizational data

### XSS Prevention
- All user input is HTML-escaped before rendering
- No `innerHTML` with unsanitized data
- Proper attribute escaping in generated HTML

## Technical Details

### Browser Compatibility
- Chrome/Edge 90+
- Firefox 88+
- Safari 14+
- Any modern browser with ES6 support

### Performance
- Handles scenarios with hundreds of nodes efficiently
- Instant recalculation on state changes
- No noticeable lag even with complex inheritance chains

### File Size
- Current version: ~49 KB
- Zero dependencies
- Loads instantly from local filesystem

### File Structure

```
/home/boc/tools/spperms/
├── index.html                          # Main application (48KB)
├── sharepointpermissions.html1stbak    # Backup of older version
├── README.md                           # This file - overview and features
├── ARCHITECTURE.md                     # Technical architecture documentation
├── API_REFERENCE.md                    # Complete function reference
├── USER_GUIDE.md                       # Practical usage guide
├── DEPLOYMENT.md                       # Production deployment & operations
├── Caddyfile                           # Web server configuration
├── permissions-fyi-caddy.service       # Systemd service definition
└── caddy-access.log                    # Web server access logs
```

### Schema Versioning
Current schema version: **2**

**v1 → v2 Migration**: Automatic addition of `sharingLinks` array to nodes that lack it.

## Keyboard Shortcuts

- **Escape**: Close help popover

## Export Formats

### JSON Export
Complete scenario including:
- All principals (users, groups, externals)
- Full node tree with relationships
- Permission assignments
- Sharing links
- Current selection

Use for: Sharing scenarios, version control, backups

### CSV Export
Audit report with columns:
- Path (full hierarchy path)
- Type (site/library/folder/file)
- Inherits (Yes/No)
- Risk Level (High/Medium/Low)
- Risk Note (explanation)
- Unique Permissions (list of direct assignments)
- Sharing Links (list of active links)

Use for: Compliance reporting, Excel analysis, documentation

## Limitations

### Not Modeled
- Item-level permissions (all items use same 5 roles)
- Limited permissions (limited access to specific lists)
- Anonymous user tracking
- Time-based permission expiration
- SharePoint groups vs M365 groups distinction
- Permission level customization (custom roles)
- Actual file content or metadata

### Simplified Behaviors
- No distinction between list-level and folder-level permissions
- Group membership is implicit (groups are atomic units)
- External sharing requires admin enablement (assumed enabled)
- Cross-site collection access not modeled

## Troubleshooting

### Can't see changes
- Make sure the item is selected in the middle panel
- Check that you clicked the action button (not just filled the form)
- Look for the flash animation indicating the update

### Unexpected permissions
- Check the inheritance chain - item might be inheriting from parent
- Look for sharing links (📤 indicator) - they bypass broken inheritance
- Verify the selected item in middle panel matches the one you're editing

### Export not working
- Ensure browser allows downloads from local files
- Try a different browser
- Check browser console for errors

### Import fails
- Verify JSON file is valid (try opening in text editor)
- Ensure file came from this tool (not hand-edited)
- Check for schema version mismatch

## Self-Test

The tool includes built-in self-tests to verify core logic:
1. Click "Run Self-Test" button
2. Tests verify:
   - Permission assignment
   - Inheritance behavior
   - Broken inheritance blocking
   - Child inheritance from unique parent
3. Results shown in alert and console

Tests run in a snapshot, original state is restored after testing.

## Development Notes

### Why One File?
- **Portability**: Send via email, copy to USB, no installation
- **Security**: No external dependencies to compromise
- **Simplicity**: View source to understand completely
- **Offline**: Works without internet connection
- **Trust**: Audit the entire codebase in minutes

### Design Patterns
- **IIFE**: Immediately Invoked Function Expression encapsulates all logic
- **State Management**: Single source of truth in `app.state` object
- **Unidirectional Data Flow**: User action → state update → re-render
- **Declarative Rendering**: HTML generated from state, not manipulated
- **Event Delegation**: Event handlers bound after each render

### Styling Approach
- **CSS Custom Properties**: Theme colors defined in `:root`
- **Dark Theme**: Easy on the eyes for extended use
- **Semantic Colors**: `--ok`, `--warn`, `--bad` for risk levels
- **Responsive Grid**: Adapts from 3-column desktop to stacked mobile
- **No CSS Framework**: Lightweight, custom styles only

## Future Enhancements

Potential improvements (not currently implemented):

- [ ] Undo/redo functionality
- [ ] Permission comparison mode (before/after)
- [ ] Search/filter in large scenarios
- [ ] Print-friendly view
- [ ] Dark/light theme toggle
- [ ] Keyboard navigation in tree
- [ ] Drag-and-drop to reorganize
- [ ] Permission diff view
- [ ] Time-based link expiration
- [ ] Graph visualization of permission flow
- [ ] Import from actual SharePoint (would require backend)

## Contributing

This is a self-contained educational tool. To contribute:

1. Make changes to `sharepointpermissions.html`
2. Test thoroughly with various scenarios
3. Run self-test to verify core logic
4. Test in multiple browsers
5. Document changes in comments
6. Keep it as a single file (maintain simplicity)

## License

No license information included in the source. Appears to be a proprietary tool for educational/consulting use.

## Support & Contact

The tool includes a link to `https://internacious.com` for booking permissions reviews, suggesting commercial support availability.

## Credits

Developed as an interactive training tool for understanding SharePoint permissions inheritance and effective access calculation.

## Version History

### Version 2 (Current - sharepointpermissions.html)
- Added sharing links support
- Implemented inheritance bypass behavior for links
- Enhanced risk assessment for link-based risks
- Added visual indicators for sharing links
- Warning boxes for dangerous SharePoint behaviors
- CSV export includes sharing link information
- Schema migration from v1

### Version 1 (Backup - sharepointpermissions.html1stbak)
- Initial release with basic inheritance model
- Direct permission assignments only
- No sharing links

---

## Quick Reference Card

### Role Hierarchy (Lowest to Highest)
```
None → Read → Contribute → Edit → Full Control
```

### Node Hierarchy (Must follow this structure)
```
Site
└── Library (only under Site)
    └── Folder (under Library or Folder)
        └── File (under Library or Folder)
```

### Risk Levels
| Level | Triggers | Color |
|-------|----------|-------|
| High | "Anyone" links, Links bypassing inheritance, External Edit+ | Red |
| Medium | Broken inheritance + many editors (5+) | Yellow |
| Low | No obvious risks | Green |

### Inheritance Behavior
- **Enabled (inherits)**: Gets permissions from parent + own assignments
- **Disabled (unique)**: Only own assignments (parent blocked)
- **Sharing Links**: ALWAYS walk to root, bypass broken inheritance

### Three-Panel Workflow
1. **Build** (Left): Edit selected item, manage people, toggle inheritance
2. **Structure** (Middle): View and select items in the tree
3. **Effective** (Right): See who can access and why
