1
0
mirror of https://github.com/bitwarden/server.git synced 2025-01-08 19:47:44 +01:00
bitwarden-server/src/Api/Controllers/CiphersController.cs

552 lines
22 KiB
C#
Raw Normal View History

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Bit.Core.Repositories;
using Microsoft.AspNetCore.Authorization;
2017-03-09 03:55:08 +01:00
using Bit.Core.Models.Api;
using Bit.Core.Exceptions;
using Bit.Core.Services;
2017-04-12 18:42:00 +02:00
using Bit.Core;
using Bit.Api.Utilities;
2017-07-10 20:30:12 +02:00
using Bit.Core.Utilities;
using System.Collections.Generic;
2017-10-26 03:38:54 +02:00
using Bit.Core.Models.Table;
namespace Bit.Api.Controllers
{
[Route("ciphers")]
[Authorize("Application")]
public class CiphersController : Controller
{
private readonly ICipherRepository _cipherRepository;
2017-04-27 15:19:30 +02:00
private readonly ICollectionCipherRepository _collectionCipherRepository;
private readonly ICipherService _cipherService;
private readonly IUserService _userService;
2017-04-12 18:42:00 +02:00
private readonly CurrentContext _currentContext;
2017-07-01 05:01:41 +02:00
private readonly GlobalSettings _globalSettings;
public CiphersController(
ICipherRepository cipherRepository,
2017-04-27 15:19:30 +02:00
ICollectionCipherRepository collectionCipherRepository,
ICipherService cipherService,
2017-04-12 18:42:00 +02:00
IUserService userService,
2017-07-01 05:01:41 +02:00
CurrentContext currentContext,
GlobalSettings globalSettings)
{
_cipherRepository = cipherRepository;
2017-04-27 15:19:30 +02:00
_collectionCipherRepository = collectionCipherRepository;
_cipherService = cipherService;
_userService = userService;
2017-04-12 18:42:00 +02:00
_currentContext = currentContext;
2017-07-01 05:01:41 +02:00
_globalSettings = globalSettings;
}
[HttpGet("{id}")]
2017-03-01 04:51:29 +01:00
public async Task<CipherResponseModel> Get(string id)
{
2017-02-18 07:17:09 +01:00
var userId = _userService.GetProperUserId(User).Value;
2017-03-01 04:51:29 +01:00
var cipher = await _cipherRepository.GetByIdAsync(new Guid(id), userId);
if(cipher == null)
{
throw new NotFoundException();
}
2017-07-01 05:01:41 +02:00
return new CipherResponseModel(cipher, _globalSettings);
}
[HttpGet("{id}/admin")]
public async Task<CipherResponseModel> GetAdmin(string id)
{
var cipher = await _cipherRepository.GetDetailsByIdAsync(new Guid(id));
if(cipher == null || !cipher.OrganizationId.HasValue ||
!_currentContext.OrganizationAdmin(cipher.OrganizationId.Value))
{
throw new NotFoundException();
}
return new CipherResponseModel(cipher, _globalSettings);
}
2017-04-04 23:22:47 +02:00
[HttpGet("{id}/full-details")]
2017-05-07 05:23:01 +02:00
[HttpGet("{id}/details")]
public async Task<CipherDetailsResponseModel> GetDetails(string id)
2017-04-04 23:22:47 +02:00
{
var userId = _userService.GetProperUserId(User).Value;
var cipherId = new Guid(id);
2017-05-07 05:23:01 +02:00
var cipher = await _cipherRepository.GetByIdAsync(cipherId, userId);
2017-04-04 23:22:47 +02:00
if(cipher == null)
{
throw new NotFoundException();
}
2017-04-27 15:19:30 +02:00
var collectionCiphers = await _collectionCipherRepository.GetManyByUserIdCipherIdAsync(userId, cipherId);
2017-07-01 05:01:41 +02:00
return new CipherDetailsResponseModel(cipher, _globalSettings, collectionCiphers);
2017-04-04 23:22:47 +02:00
}
[HttpGet("")]
public async Task<ListResponseModel<CipherDetailsResponseModel>> Get()
{
2017-02-18 07:17:09 +01:00
var userId = _userService.GetProperUserId(User).Value;
var hasOrgs = _currentContext.Organizations?.Any() ?? false;
2018-04-25 02:19:23 +02:00
// TODO: Use hasOrgs proper for cipher listing here?
var ciphers = await _cipherRepository.GetManyByUserIdAsync(userId, true || hasOrgs);
Dictionary<Guid, IGrouping<Guid, CollectionCipher>> collectionCiphersGroupDict = null;
if(hasOrgs)
{
var collectionCiphers = await _collectionCipherRepository.GetManyByUserIdAsync(userId);
collectionCiphersGroupDict = collectionCiphers.GroupBy(c => c.CipherId).ToDictionary(s => s.Key);
}
var responses = ciphers.Select(c => new CipherDetailsResponseModel(c, _globalSettings,
collectionCiphersGroupDict)).ToList();
return new ListResponseModel<CipherDetailsResponseModel>(responses);
}
[HttpPost("")]
public async Task<CipherResponseModel> Post([FromBody]CipherRequestModel model)
{
var userId = _userService.GetProperUserId(User).Value;
var cipher = model.ToCipherDetails(userId);
if(cipher.OrganizationId.HasValue && !_currentContext.OrganizationUser(cipher.OrganizationId.Value))
{
throw new NotFoundException();
}
await _cipherService.SaveDetailsAsync(cipher, userId, null, cipher.OrganizationId.HasValue);
var response = new CipherResponseModel(cipher, _globalSettings);
return response;
}
[HttpPost("create")]
public async Task<CipherResponseModel> PostCreate([FromBody]CipherCreateRequestModel model)
{
var userId = _userService.GetProperUserId(User).Value;
var cipher = model.Cipher.ToCipherDetails(userId);
if(cipher.OrganizationId.HasValue && !_currentContext.OrganizationUser(cipher.OrganizationId.Value))
{
throw new NotFoundException();
}
await _cipherService.SaveDetailsAsync(cipher, userId, model.CollectionIds, cipher.OrganizationId.HasValue);
var response = new CipherResponseModel(cipher, _globalSettings);
return response;
}
[HttpPost("admin")]
public async Task<CipherMiniResponseModel> PostAdmin([FromBody]CipherCreateRequestModel model)
{
var cipher = model.Cipher.ToOrganizationCipher();
if(!_currentContext.OrganizationAdmin(cipher.OrganizationId.Value))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User).Value;
await _cipherService.SaveAsync(cipher, userId, model.CollectionIds, true, false);
var response = new CipherMiniResponseModel(cipher, _globalSettings, false);
return response;
}
[HttpPut("{id}")]
[HttpPost("{id}")]
public async Task<CipherResponseModel> Put(string id, [FromBody]CipherRequestModel model)
{
var userId = _userService.GetProperUserId(User).Value;
var cipher = await _cipherRepository.GetByIdAsync(new Guid(id), userId);
if(cipher == null)
{
throw new NotFoundException();
}
2018-10-22 20:07:17 +02:00
var modelOrgId = string.IsNullOrWhiteSpace(model.OrganizationId) ?
(Guid?)null : new Guid(model.OrganizationId);
if(cipher.OrganizationId != modelOrgId)
{
throw new BadRequestException("Organization mismatch. Re-sync if you recently shared this item, " +
"then try again.");
}
await _cipherService.SaveDetailsAsync(model.ToCipherDetails(cipher), userId);
var response = new CipherResponseModel(cipher, _globalSettings);
return response;
}
[HttpPut("{id}/admin")]
[HttpPost("{id}/admin")]
public async Task<CipherMiniResponseModel> PutAdmin(string id, [FromBody]CipherRequestModel model)
{
var userId = _userService.GetProperUserId(User).Value;
var cipher = await _cipherRepository.GetDetailsByIdAsync(new Guid(id));
if(cipher == null || !cipher.OrganizationId.HasValue ||
!_currentContext.OrganizationAdmin(cipher.OrganizationId.Value))
{
throw new NotFoundException();
}
// object cannot be a descendant of CipherDetails, so let's clone it.
var cipherClone = CoreHelpers.CloneObject(model.ToCipher(cipher));
await _cipherService.SaveAsync(cipherClone, userId, null, true, false);
var response = new CipherMiniResponseModel(cipherClone, _globalSettings, cipher.OrganizationUseTotp);
return response;
}
2017-04-17 23:01:23 +02:00
[HttpGet("organization-details")]
2018-10-22 20:07:17 +02:00
public async Task<ListResponseModel<CipherMiniDetailsResponseModel>> GetOrganizationCollections(
string organizationId)
2017-04-17 23:01:23 +02:00
{
var userId = _userService.GetProperUserId(User).Value;
var orgIdGuid = new Guid(organizationId);
if(!_currentContext.OrganizationAdmin(orgIdGuid))
{
throw new NotFoundException();
}
var ciphers = await _cipherRepository.GetManyByOrganizationIdAsync(orgIdGuid);
2017-04-27 15:19:30 +02:00
var collectionCiphers = await _collectionCipherRepository.GetManyByOrganizationIdAsync(orgIdGuid);
2017-04-27 15:39:21 +02:00
var collectionCiphersGroupDict = collectionCiphers.GroupBy(c => c.CipherId).ToDictionary(s => s.Key);
2017-04-17 23:01:23 +02:00
2017-07-01 05:01:41 +02:00
var responses = ciphers.Select(c => new CipherMiniDetailsResponseModel(c, _globalSettings,
collectionCiphersGroupDict));
2017-04-17 23:01:23 +02:00
return new ListResponseModel<CipherMiniDetailsResponseModel>(responses);
}
[HttpPost("import")]
public async Task PostImport([FromBody]ImportCiphersRequestModel model)
{
if(!_globalSettings.SelfHosted &&
(model.Ciphers.Count() > 5000 || model.FolderRelationships.Count() > 5000 ||
model.Folders.Count() > 200))
2017-10-09 22:58:37 +02:00
{
throw new BadRequestException("You cannot import this much data at once.");
}
var userId = _userService.GetProperUserId(User).Value;
2017-05-07 05:45:29 +02:00
var folders = model.Folders.Select(f => f.ToFolder(userId)).ToList();
var ciphers = model.Ciphers.Select(c => c.ToCipherDetails(userId, false)).ToList();
2017-06-13 15:12:00 +02:00
await _cipherService.ImportCiphersAsync(folders, ciphers, model.FolderRelationships);
}
2017-09-06 15:06:13 +02:00
[HttpPost("import-organization")]
2018-10-22 20:07:17 +02:00
public async Task PostImport([FromQuery]string organizationId,
[FromBody]ImportOrganizationCiphersRequestModel model)
{
if(!_globalSettings.SelfHosted &&
(model.Ciphers.Count() > 5000 || model.CollectionRelationships.Count() > 5000 ||
model.Collections.Count() > 200))
2017-10-09 22:58:37 +02:00
{
throw new BadRequestException("You cannot import this much data at once.");
}
2017-09-06 15:06:13 +02:00
var orgId = new Guid(organizationId);
if(!_currentContext.OrganizationAdmin(orgId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User).Value;
2017-09-06 15:06:13 +02:00
var collections = model.Collections.Select(c => c.ToCollection(orgId)).ToList();
2017-09-28 19:11:56 +02:00
var ciphers = model.Ciphers.Select(l => l.ToOrganizationCipherDetails(orgId)).ToList();
await _cipherService.ImportCiphersAsync(collections, ciphers, model.CollectionRelationships, userId);
}
[HttpPut("{id}/partial")]
[HttpPost("{id}/partial")]
public async Task PutPartial(string id, [FromBody]CipherPartialRequestModel model)
{
var userId = _userService.GetProperUserId(User).Value;
var folderId = string.IsNullOrWhiteSpace(model.FolderId) ? null : (Guid?)new Guid(model.FolderId);
await _cipherRepository.UpdatePartialAsync(new Guid(id), userId, folderId, model.Favorite);
}
2017-04-12 18:42:00 +02:00
[HttpPut("{id}/share")]
[HttpPost("{id}/share")]
2018-10-23 22:12:31 +02:00
public async Task<CipherResponseModel> PutShare(string id, [FromBody]CipherShareRequestModel model)
{
var userId = _userService.GetProperUserId(User).Value;
2018-10-23 22:12:31 +02:00
var cipherId = new Guid(id);
var cipher = await _cipherRepository.GetByIdAsync(cipherId);
2017-04-12 18:42:00 +02:00
if(cipher == null || cipher.UserId != userId ||
!_currentContext.OrganizationUser(new Guid(model.Cipher.OrganizationId)))
{
throw new NotFoundException();
}
2017-07-10 20:30:12 +02:00
var original = CoreHelpers.CloneObject(cipher);
2018-10-22 20:07:17 +02:00
await _cipherService.ShareAsync(original, model.Cipher.ToCipher(cipher),
new Guid(model.Cipher.OrganizationId), model.CollectionIds.Select(c => new Guid(c)), userId);
2018-10-23 22:12:31 +02:00
var sharedCipher = await _cipherRepository.GetByIdAsync(cipherId, userId);
var response = new CipherResponseModel(sharedCipher, _globalSettings);
return response;
}
2017-04-27 15:19:30 +02:00
[HttpPut("{id}/collections")]
[HttpPost("{id}/collections")]
public async Task PutCollections(string id, [FromBody]CipherCollectionsRequestModel model)
2017-04-12 18:42:00 +02:00
{
var userId = _userService.GetProperUserId(User).Value;
var cipher = await _cipherRepository.GetByIdAsync(new Guid(id), userId);
if(cipher == null || !cipher.OrganizationId.HasValue ||
!_currentContext.OrganizationUser(cipher.OrganizationId.Value))
{
throw new NotFoundException();
}
2018-10-22 20:07:17 +02:00
await _cipherService.SaveCollectionsAsync(cipher,
model.CollectionIds.Select(c => new Guid(c)), userId, false);
2017-04-18 05:12:48 +02:00
}
2017-04-27 15:19:30 +02:00
[HttpPut("{id}/collections-admin")]
[HttpPost("{id}/collections-admin")]
public async Task PutCollectionsAdmin(string id, [FromBody]CipherCollectionsRequestModel model)
2017-04-18 05:12:48 +02:00
{
var userId = _userService.GetProperUserId(User).Value;
var cipher = await _cipherRepository.GetByIdAsync(new Guid(id));
if(cipher == null || !cipher.OrganizationId.HasValue ||
!_currentContext.OrganizationAdmin(cipher.OrganizationId.Value))
{
throw new NotFoundException();
}
2018-10-22 20:07:17 +02:00
await _cipherService.SaveCollectionsAsync(cipher,
model.CollectionIds.Select(c => new Guid(c)), userId, true);
2017-04-12 18:42:00 +02:00
}
[HttpDelete("{id}")]
[HttpPost("{id}/delete")]
public async Task Delete(string id)
{
2017-03-22 02:13:20 +01:00
var userId = _userService.GetProperUserId(User).Value;
var cipher = await _cipherRepository.GetByIdAsync(new Guid(id), userId);
if(cipher == null)
{
throw new NotFoundException();
}
await _cipherService.DeleteAsync(cipher, userId);
}
2017-04-19 22:00:47 +02:00
[HttpDelete("{id}/admin")]
[HttpPost("{id}/delete-admin")]
public async Task DeleteAdmin(string id)
{
var userId = _userService.GetProperUserId(User).Value;
var cipher = await _cipherRepository.GetByIdAsync(new Guid(id));
if(cipher == null || !cipher.OrganizationId.HasValue ||
!_currentContext.OrganizationAdmin(cipher.OrganizationId.Value))
{
throw new NotFoundException();
}
await _cipherService.DeleteAsync(cipher, userId, true);
}
2017-06-09 06:30:59 +02:00
[HttpDelete("")]
[HttpPost("delete")]
public async Task DeleteMany([FromBody]CipherBulkDeleteRequestModel model)
{
2017-11-17 02:05:06 +01:00
if(!_globalSettings.SelfHosted && model.Ids.Count() > 500)
2017-10-09 22:58:37 +02:00
{
2017-11-28 15:21:32 +01:00
throw new BadRequestException("You can only delete up to 500 items at a time. " +
"Consider using the \"Purge Vault\" option instead.");
2017-10-09 22:58:37 +02:00
}
2017-06-09 06:30:59 +02:00
var userId = _userService.GetProperUserId(User).Value;
await _cipherService.DeleteManyAsync(model.Ids.Select(i => new Guid(i)), userId);
}
[HttpPut("move")]
[HttpPost("move")]
public async Task MoveMany([FromBody]CipherBulkMoveRequestModel model)
{
2017-11-17 02:05:06 +01:00
if(!_globalSettings.SelfHosted && model.Ids.Count() > 500)
2017-10-09 22:58:37 +02:00
{
2017-11-17 02:05:06 +01:00
throw new BadRequestException("You can only move up to 500 items at a time.");
2017-10-09 22:58:37 +02:00
}
2017-06-09 06:30:59 +02:00
var userId = _userService.GetProperUserId(User).Value;
await _cipherService.MoveManyAsync(model.Ids.Select(i => new Guid(i)),
string.IsNullOrWhiteSpace(model.FolderId) ? (Guid?)null : new Guid(model.FolderId), userId);
2017-06-09 06:30:59 +02:00
}
2018-06-13 20:03:44 +02:00
[HttpPut("share")]
[HttpPost("share")]
public async Task PutShareMany([FromBody]CipherBulkShareRequestModel model)
{
var organizationId = new Guid(model.Ciphers.First().OrganizationId);
if(!_currentContext.OrganizationUser(organizationId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User).Value;
var ciphers = await _cipherRepository.GetManyByUserIdAsync(userId, false);
var ciphersDict = ciphers.ToDictionary(c => c.Id);
var shareCiphers = new List<Cipher>();
foreach(var cipher in model.Ciphers)
{
if(!ciphersDict.ContainsKey(cipher.Id.Value))
2018-06-13 20:03:44 +02:00
{
throw new BadRequestException("Trying to share ciphers that you do not own.");
}
shareCiphers.Add(cipher.ToCipher(ciphersDict[cipher.Id.Value]));
2018-06-13 20:03:44 +02:00
}
await _cipherService.ShareManyAsync(shareCiphers, organizationId,
model.CollectionIds.Select(c => new Guid(c)), userId);
}
2017-10-26 03:26:09 +02:00
[HttpPost("purge")]
2018-09-25 15:12:50 +02:00
public async Task PostPurge([FromBody]CipherPurgeRequestModel model, string organizationId = null)
2017-10-26 03:26:09 +02:00
{
2017-10-26 03:38:54 +02:00
var user = await _userService.GetUserByPrincipalAsync(User);
if(user == null)
{
throw new UnauthorizedAccessException();
}
2018-04-17 14:10:17 +02:00
if(!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash))
2017-10-26 03:38:54 +02:00
{
ModelState.AddModelError("MasterPasswordHash", "Invalid password.");
await Task.Delay(2000);
throw new BadRequestException(ModelState);
}
2018-09-25 15:12:50 +02:00
if(string.IsNullOrWhiteSpace(organizationId))
{
await _cipherRepository.DeleteByUserIdAsync(user.Id);
}
else
{
var orgId = new Guid(organizationId);
if(!_currentContext.OrganizationAdmin(orgId))
{
throw new NotFoundException();
}
await _cipherService.PurgeAsync(orgId);
}
2017-10-26 03:26:09 +02:00
}
[HttpPost("{id}/attachment")]
[RequestSizeLimit(105_906_176)]
[DisableFormValueModelBinding]
public async Task<CipherResponseModel> PostAttachment(string id)
{
2017-07-10 20:30:12 +02:00
ValidateAttachment();
var idGuid = new Guid(id);
var userId = _userService.GetProperUserId(User).Value;
var cipher = await _cipherRepository.GetByIdAsync(idGuid, userId);
if(cipher == null)
{
2017-07-10 20:30:12 +02:00
throw new NotFoundException();
}
await Request.GetFileAsync(async (stream, fileName, key) =>
2017-07-01 05:01:41 +02:00
{
await _cipherService.CreateAttachmentAsync(cipher, stream, fileName, key,
2017-07-10 20:30:12 +02:00
Request.ContentLength.GetValueOrDefault(0), userId);
});
return new CipherResponseModel(cipher, _globalSettings);
2017-07-10 20:30:12 +02:00
}
2018-02-24 20:29:11 +01:00
[HttpPost("{id}/attachment-admin")]
[RequestSizeLimit(105_906_176)]
2018-02-24 20:29:11 +01:00
[DisableFormValueModelBinding]
public async Task<CipherResponseModel> PostAttachmentAdmin(string id)
{
ValidateAttachment();
2018-02-24 20:32:48 +01:00
var idGuid = new Guid(id);
2018-02-24 20:29:11 +01:00
var userId = _userService.GetProperUserId(User).Value;
2018-02-24 20:32:48 +01:00
var cipher = await _cipherRepository.GetDetailsByIdAsync(idGuid);
2018-02-24 20:29:11 +01:00
if(cipher == null || !cipher.OrganizationId.HasValue ||
!_currentContext.OrganizationAdmin(cipher.OrganizationId.Value))
{
throw new NotFoundException();
}
await Request.GetFileAsync(async (stream, fileName, key) =>
2018-02-24 20:29:11 +01:00
{
await _cipherService.CreateAttachmentAsync(cipher, stream, fileName, key,
2018-02-24 20:29:11 +01:00
Request.ContentLength.GetValueOrDefault(0), userId);
});
return new CipherResponseModel(cipher, _globalSettings);
}
2017-07-10 20:30:12 +02:00
[HttpPost("{id}/attachment/{attachmentId}/share")]
[RequestSizeLimit(105_906_176)]
2017-07-10 20:30:12 +02:00
[DisableFormValueModelBinding]
public async Task PostAttachmentShare(string id, string attachmentId, Guid organizationId)
{
ValidateAttachment();
2017-07-01 05:01:41 +02:00
var userId = _userService.GetProperUserId(User).Value;
2017-07-10 20:30:12 +02:00
var cipher = await _cipherRepository.GetByIdAsync(new Guid(id));
if(cipher == null || cipher.UserId != userId || !_currentContext.OrganizationUser(organizationId))
{
throw new NotFoundException();
}
await Request.GetFileAsync(async (stream, fileName, key) =>
{
await _cipherService.CreateAttachmentShareAsync(cipher, stream,
2017-07-10 20:30:12 +02:00
Request.ContentLength.GetValueOrDefault(0), attachmentId, organizationId);
});
}
[HttpDelete("{id}/attachment/{attachmentId}")]
[HttpPost("{id}/attachment/{attachmentId}/delete")]
public async Task DeleteAttachment(string id, string attachmentId)
{
var idGuid = new Guid(id);
var userId = _userService.GetProperUserId(User).Value;
var cipher = await _cipherRepository.GetByIdAsync(idGuid, userId);
if(cipher == null)
{
throw new NotFoundException();
}
2017-07-07 17:07:22 +02:00
await _cipherService.DeleteAttachmentAsync(cipher, attachmentId, userId, false);
}
2017-07-10 20:30:12 +02:00
2018-02-24 20:29:11 +01:00
[HttpDelete("{id}/attachment/{attachmentId}/admin")]
[HttpPost("{id}/attachment/{attachmentId}/delete-admin")]
public async Task DeleteAttachmentAdmin(string id, string attachmentId)
{
var idGuid = new Guid(id);
var userId = _userService.GetProperUserId(User).Value;
var cipher = await _cipherRepository.GetByIdAsync(idGuid);
if(cipher == null || !cipher.OrganizationId.HasValue ||
!_currentContext.OrganizationAdmin(cipher.OrganizationId.Value))
{
throw new NotFoundException();
}
await _cipherService.DeleteAttachmentAsync(cipher, attachmentId, userId, false);
}
2017-07-10 20:30:12 +02:00
private void ValidateAttachment()
{
if(!Request?.ContentType.Contains("multipart/") ?? true)
{
throw new BadRequestException("Invalid content.");
}
if(Request.ContentLength > 105906176) // 101 MB, give em' 1 extra MB for cushion
{
throw new BadRequestException("Max file size is 100 MB.");
}
}
}
}