Compartilhar via


SDK de Arquivo se Proteção de Informações da Microsoft – justificativa de ação para rebaixamento de rótulo de confidencialidade em um arquivo (C++)

Este início rápido aborda o tratamento de uma operação de downgrade de rótulo quando a política de rótulo exigir justificativa. Agora usaremos a classe mip::FileHandler para alterar os rótulos de um arquivo. Para obter mais detalhes, consulte SDK da MIP (Proteção de Informações da Microsoft) para C++: Referência.

Pré-requisitos

Conclua os seguintes pré-requisitos antes de continuar, caso ainda não tenha feito isso:

Adicionar lógica para definir um rótulo inferior a um arquivo protegido

Adicione lógica para definir um rótulo de sensibilidade em um arquivo, usando o objeto mip::FileHandler.

  1. Abra a solução do Visual Studio criada no Início Rápido: definir/obter rótulos de confidencialidade (C++) anterior.

  2. Usando o Gerenciador de Soluções, abra o arquivo .cpp no projeto que contém a implementação do método main(). Ele usa como padrão o mesmo nome que o projeto em que está contido, que você especificou durante a criação do projeto.

  3. Adicione as seguintes diretivas #include e using, abaixo das diretivas existentes correspondentes, na parte superior do arquivo:

    
        #include "mip/file/file_error.h"
    
        using mip::JustificationRequiredError;
        using std::cin;
    
    
  4. Atualize o valor <label-id> do início rápido anterior para um rótulo de confidencialidade que exija justificativa para rebaixamento. No decorrer deste início rápido, definiremos o rótulo primeiro e, depois disso, tentaremos rebaixá-lo por meio de snippets de código em outras etapas.

  5. Perto do final do corpo main(), abaixo de system("pause"); e acima do bloco de desligamento (de onde você parou no Início Rápido anterior), insira o seguinte código:


// Downgrade label
// Set paths and lower label ID
// Set a new label on input file.

string lowerlabelId = "<lower-label-id>";
cout << "\nApplying new Label ID " << lowerlabelId << " to " << filePathOut << endl;
mip::LabelingOptions labelingOptions(mip::AssignmentMethod::PRIVILEGED);

// Try to apply a label with lower sensitivity.
try
{
    handler->SetLabel(engine->GetLabelById(lowerlabelId), labelingOptions, mip::ProtectionSettings());
}

catch (const mip::JustificationRequiredError& e)
{
    // Request justification from user.
    cout<<"Please provide justification for downgrading a label: "<<endl;
    string justification;
    cin >> justification;

    // Set Justification provided flag
    bool isDowngradeJustified = true;
    mip::LabelingOptions labelingOptions(mip::AssignmentMethod::PRIVILEGED);
    labelingOptions.SetDowngradeJustification(isDowngradeJustified,justification);

    //Set new label.
    handler->SetLabel(engine->GetLabelById(lowerlabelId), labelingOptions, mip::ProtectionSettings());
}

catch (const std::exception& e)
{
    cout << "An exception occurred... did you specify a valid label ID?\n\n" << e.what() << "'\n";
    system("pause");
    return 1;
}

// Commit changes, save as a different output file
string lowerFilePathOut = "<lower-output-file-path>";
try
{
    cout << "Committing changes" << endl;
    auto commitPromise = std::make_shared<std::promise<bool>>();
    auto commitFuture = commitPromise->get_future();
    handler->CommitAsync(lowerFilePathOut, commitPromise);
    if (commitFuture.get()) {
        cout << "\nLabel committed to file: " << lowerFilePathOut << endl;
    }
    else {
        cout << "Failed to label: " + lowerFilePathOut << endl;
        return 1;
    }
}
catch (const std::exception& e)
{
    cout << "An exception occurred... did you specify a valid commit file path?\n\n" << e.what() << "'\n";
    system("pause");
    return 1;
}
system("pause");

// Set up async FileHandler for output file operations
string lowerActualFilePath = "<lower-content-identifier>";
try
{
    auto handlerPromise = std::make_shared<std::promise<std::shared_ptr<FileHandler>>>();
    auto handlerFuture = handlerPromise->get_future();
    engine->CreateFileHandlerAsync(
        lowerFilePathOut,
        lowerActualFilePath,
        true,
        std::make_shared<FileHandlerObserver>(),
        handlerPromise);

    handler = handlerFuture.get();
}
catch (const std::exception& e)
{
    cout << "An exception occurred... did you specify a valid output file path?\n\n" << e.what() << "'\n";
    system("pause");
    return 1;
}

// Get the lowered label from output file
try
{
    cout << "\nGetting the label committed to file: " << lowerFilePathOut << endl;
    auto lowerLabel = handler->GetLabel();
    cout << "Name: " + lowerLabel->GetLabel()->GetName() << endl;
    cout << "Id: " + lowerLabel->GetLabel()->GetId() << endl;
}
catch (const std::exception& e)
{
    cout << "An exception occurred... did you specify a valid label ID?\n\n" << e.what() << "'\n";
    system("pause");
    return 1;
}
system("pause");

  1. Substitua os valores de espaço reservado no código-fonte usando os seguintes valores:

    Espaço reservado Valor
    <lower-label-id> Uma ID de rótulo, copiada da saída do console no Início Rápido anterior. Por exemplo: bb7ed207-046a-4caf-9826-647cff56b990. Garanta que ele tenha menos confidencialidade do que o rótulo de arquivo protegido anteriormente.
    <lower-output-file-path> O caminho do arquivo de saída no qual você deseja salvar o arquivo modificado.
    <lower-content-identifier> Um identificador legível por humanos para o conteúdo.

Criar e testar o aplicativo

Crie e teste o aplicativo cliente.

  1. Use CTRL-SHIFT-B (Compilar solução) para compilar o aplicativo cliente. Se não houver erros de build, use F5 (Iniciar depuração) para executar o aplicativo.

  2. Se o projeto for compilado e executado com êxito, o aplicativo solicitará um token de acesso cada vez que o SDK chamar seu método AcquireOAuth2Token().

  Non-Business : 87ba5c36-17cf-14793-bbc2-bd5b3a9f95cz
  Public : 83867195-f2b8-2ac2-b0b6-6bb73cb33afz
  General : f42a3342-8706-4288-bd31-ebb85995028z
  Confidential : 074e457c-5848-4542-9a6f-34a182080e7z
  Highly Confidential : f55c2dea-db0f-47cd-8520-a52e1590fb6z
  Press any key to continue . . .

  Applying Label ID f55c2dea-db0f-47cd-8520-a52e1590fb6z to c:\Test\Test.docx
  Committing changes


  Label committed to file: c:\Test\Test.docx
  Press any key to continue . . .

  Run the PowerShell script to generate an access token using the following values, then copy/paste it below:
  Set $authority to: https://login.windows.net/37f4583d-9985-4e7f-a1ab-71afd8b55ba0
  Set $resourceUrl to: https://aadrm.com
  Sign in with user account: user1@tenant.onmicrosoft.com
  Enter access token: <paste-access-token-here>
  Press any key to continue . . .

  Getting the label committed to file: c:\Test\Test_labeled.docx
  Name: Highly Confidential
  Id: f55c2dea-db0f-47cd-8520-a52e1590fb6z
  Press any key to continue . . . 

  Applying new Label ID f42a3342-8706-4288-bd31-ebb85995028z to c:\Test\Test_labeled.docx
  Please provide justification for downgrading a label:
  Need for sharing with wider audience.
  Committing changes

  Label committed to file: c:\Test\Test_downgraded.docx
  Press any key to continue . . .

  Getting the label committed to file: c:\Test\Test_downgraded.docx
  Name: General
  Id: f42a3342-8706-4288-bd31-ebb85995028z
  Press any key to continue . . .

Observe que uma abordagem semelhante também se aplica à operação DeleteLabel(), caso o rótulo que está sendo excluído de um arquivo exija uma justificativa de acordo com a política do rótulo. A função DeleteLabel() lança uma exceção mip::JustificationRequiredError. O sinalizador isDowngradeJustified deve ser definido como verdadeiro no tratamento de exceção antes de excluir o rótulo com sucesso.